开发者

Get previous form filled data in Django forms

开发者 https://www.devze.com 2023-03-26 02:11 出处:网络
I use a custom template to display my form: ... <td>Username</td> <td><input id=\"id_username\" type=\"text\" maxlength=\"30\" name=\"username\" tabindex=\"1\"></td开发者_J

I use a custom template to display my form:

...
<td>Username</td>
<td><input id="id_username" type="text" maxlength="30" name="username" tabindex="1"></td开发者_JAVA技巧>
...

If I submit my registration form with (for example) a required field empty, django refresh the page and show me the error. The problem are the other fields (the correct ones). They're reset and the previous data filled in is cleared. If instead of using a custom way to display a field I use {{ form.field }} it works fine and if there's errors in the form, django fills the other correct fields.

How can I solve this?


You could try this:

forms.py

class LoginForm(forms.Form):
    username = forms.CharField(max_length = 30)
    password = forms.CharField(max_length = 30, 
               widget = forms.PasswordInput(render_value = False))

views.py

def form_post(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        c = {}
        template = "myloginform.html"
        if form.is_valid():
           # ... do stuff
        else:
           # Add the data you want to preserve here
           c['username'] = form.username
           # ...
           return render_to_response(template, c)

template myloginform.html

...
   <input id="id_username" type="text" maxlength="30" 
    name="username" tabindex="1" value="{{ username }}" />
...

Edit: To add it to the attrs dict as mentioned by Daniel above use:
uname = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'tabindex':'1', 'class': 'myclass'}))

0

精彩评论

暂无评论...
验证码 换一张
取 消