我使用自定义模板显示表单:
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> ...如果我使用(例如)必填字段提交注册表空,django刷新页面并显示错误。问题出在其他领域(正确的领域)。它们将被重置,并且先前填写的数据将被清除。如果不是使用自定义方式显示字段,而是使用 {{form.field}} ,它可以正常工作,并且如果表单中有错误,django将填充其他正确的字段。
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.
我该如何解决?
推荐答案您可以尝试
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
template myloginform.html
... <input id="id_username" type="text" maxlength="30" name="username" tabindex="1" value="{{ username }}" /> ...编辑:要将其添加到attrs字典中,如下所示: Daniel上面提到的用法: uname = form.CharField(max_length = 20,widget = forms.TextInput(attrs = {'tabindex':'1','class':'myclass' }))
更多推荐
在Django表单中获取以前的表单填充数据
发布评论