在Django表单中获取以前的表单填充数据 [英] Get previous form filled data in Django forms

查看:198
本文介绍了在Django表单中获取以前的表单填充数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用自定义模板显示表单:

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表单中获取以前的表单填充数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆