Django form(表单)的验证以及错误提示
我想用Django的form实现一个简单的用户注册功能,目前完成的界面如下:
我想完善的功能是当用户输入内容有误时,点击注册之后会在相应字段后面出现一个错误提示,就像Segmentfault的登录一样,密码错误下面会有简单的提示,如下:
我的部分代码如下,
forms.py
class SignupForm(forms.Form): username = forms.CahrField(
label=_("username"),
max_length=30,
)
email = forms.EmailField(label=_('email'),)
password_1 = forms.CharField(
label=_("password"),
widget=forms.PasswordInput,
)
password_2 = forms.CharField(
label=_("password_confirmed"),
widget=forms.PasswordInput,
)
def clean_password_2(self):
password_1 = self.cleaned_data.get("password_1")
password_2 = self.cleaned_data.get("password_2")
if password_1 and password_2 and password_1 != password_2:
raise forms.ValidationError(_('password confirm failed'))
return password_2
signup.html
<form method="post" action="{% url 'accounts:signup_post' %}"> {% csrf_token %}
<table>
{% for field in form %}
<tr>
<td>{{ field.label_tag }}</td>
<td>{{ field }}</td>
<td>{{ field.errors }}</td>
</tr>
{% endfor %}
</table>
<input type='submit' id="submit" value={% trans "signup" %}>
<a href="{% url 'accounts:login' %}">{% trans "Already have accounts?" %}</a>
</form>
views.py
def signup_post(request): if request.method == 'POST':
signup_form = forms.SignupForm(request.POST)
if signup_form.is_valid():
signup_info = signup_form.cleaned_data
username = signup_info['username']
email = signup_info['email']
password = signup_info['password_1']
user = User.objects.create_user(
username=username,
email=email,
password=password)
user.save()
# 重定向到首页(暂时没写)
else:
# 估计是这里的问题,但不知道怎么改正
return redirect(reverse("accounts:signup"))
else:
signup_form = forms.SignupForm()
return render(reverse("accounts:signup"), {'form': signup_form})
目前只是想简单验证两次输入密码是否一致,参考文档写了 clean_ 函数,但是没有成功。我猜测是views 中 signup_form.is_valid()
失败之后返回页面时需要带上form,但是不知道怎么做。
已经读了Django文档中Form部分的内容,但是仍旧找不到解决方法。
回答:
已解决。
可以看
django form field validation and error display 和 django TemplateDoesNotExist
回答:
lz可以参考这篇文章,变通实现这个功能
http://muilpin.blog.163.com/blog/static/165382936201221910158809/
ajax提交到后台,通过获取form.name.errors来确定name字段是否错误
回答:
class SignupForm(forms.Form):
email = forms.EmailField(label=u"电子邮箱")name = forms.CharField(label=u"姓名",max_length=50)
password = forms.CharField(label=u"密码", max_length=30, widget=forms.PasswordInput)
password2 = forms.CharField(label=u"确认密码", max_length=30, widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignupForm, self).clean()
password = cleaned_data.get("password")
password2 = cleaned_data.get("password2")
if password != password2:
raise forms.ValidationError(u"两次密码必须一致")
刚好也遇到了这样的问题,看了下官方的文档Cleaning and validating fields that depend on each other
希望我的回答能给以后遇到这样问题的同学提供帮助
以上是 Django form(表单)的验证以及错误提示 的全部内容, 来源链接: utcz.com/a/159967.html