Django帮助我提出验证错误

时间:2015-04-19 11:40:46

标签: django django-forms

当有人输入已经使用的用户名时,我试图创建某种警告。但是,我所要做的就是重定向到静态页面,其中包含:选择的用户名或密码不匹配。

这是我在views.py中写的:

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
        else:
            return render_to_response('invalid_reg.html')

    args = {}
    args.update(csrf(request))

    args['form'] = MyRegistrationForm()
    print args
    return render_to_response('register.html', args)

这是我的forms.py:

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()

        return user

我完全不知道如何向用户发出适当的警告。

如何在此处实施某种验证错误警告?

1 个答案:

答案 0 :(得分:1)

您可以将clean_方法添加到表单类以验证用户名字段:

def clean_username(self):
    username = self.cleaned_data.get('username')
    if username:
        user = User.objects.filter(username=username)
        if user.exists():
            raise forms.ValidationError(
                _('That username exists in our system. Please try another.'),
                code='unique_username'
            )
    return username

之后,您应该重写视图函数以将表单对象传递给注册模板:

def register_user(request):
    args = {}
    args.update(csrf(request))

    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
        else:
            args['form'] = form
            return render_to_response('register.html', args)

    args['form'] = MyRegistrationForm()
    print args
    return render_to_response('register.html', args)

我建议您了解如何在模板中显示错误消息。

Django文档中的这些页面应提供更多见解: