Get previous form filled data in Django forms
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'}))
精彩评论