在Django表单中获取以前的表单填充数据

编程入门 行业动态 更新时间:2024-10-21 20:41:58
本文介绍了在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表单中获取以前的表单填充数据

本文发布于:2023-10-28 19:28:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   数据   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!