导航菜单

python

我想用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

{% csrf_token %}{% for field in form %}{{ field.label_tag }}{{ field }}{{ field.errors }}{% endfor %}{% trans "Already have accounts?" %}

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_datausername = 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部分的内容,但是仍旧找不到解决方法。

相关推荐: