类型对象“ ModelForm”没有属性“ ValidationError”

时间:2019-01-14 20:07:27

标签: django django-forms

我正在尝试创建一个注册表单(使用Django ModelForm),以在其中验证“密码”是否正确并确认密码是否匹配。我尝试使用引发ValidationError的方法,但收到一条错误消息

类型对象'ModelForm'没有属性'ValidationError'

验证密码的正确方法应该是什么?这是我的代码如下:

models.py:

from django.db import models

class Students(models.Model):
    firstName = models.CharField(max_length=120)
    lastName = models.CharField(max_length=120)
    # studentID = models.IntegerField(null=False)
    email = models.EmailField()
    password = models.CharField(max_length=120, default="")
    password2 = models.CharField(max_length=120, default="")
    street = models.CharField(max_length=120)
    apt = models.IntegerField(blank=True, null=True)
    city = models.CharField(max_length=120)
    state = models.CharField(max_length=120)
    zipcode = models.IntegerField(null=False)

    def __str__(self):
        return self.firstName

    class Meta:
        verbose_name_plural = "Students"

forms.py:

from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _

from .models import Students


class StudentRegisterForm(ModelForm):
    class Meta:
        model = Students
        fields = [
            'firstName', 'lastName',
            'email', 'password', 'password2',
            'street', 'apt', 'city', 'state', 'zipcode',
        ]
        labels = {
            'firstName': _('First Name'),
            'lastName': _('Last Name'),
            'password2': _('Confirm Password'),
            'Apt': _('Apt/House'),
            'zipcode': _('Zip Code'),
        }


    def clean(self):
        data = self.cleaned_data
        password = self.cleaned_data.get('password')
        print(password)
        password2 = self.cleaned_data.get('password2')
        if password2 != password:
            raise ModelForm.ValidationError("Passwords must match!")
        return data

Views.py:

from django.http import HttpResponseRedirect
from django.shortcuts import render


from .models import Students
from .forms import StudentRegisterForm


def student_register(request):
    register_form = StudentRegisterForm(request.POST or None)
    context = {
        "title": "Welcome to the registration page",
        "register_form": register_form
    }
    if register_form.is_valid():
        register_form.save()


    return render(request, 'students/register.html', context)

我对编程还很陌生,所以请尝试说明我要去哪里哪里以及正确的方法是什么。谢谢!

1 个答案:

答案 0 :(得分:2)

ValidationError不是ModelForm的属性。

from django.forms import ModelForm, ValidationError

....

raise ValidationError("Passwords must match!")

或者更好:

from django import forms

class StudentRegisterForm(forms.ModelForm):

    ...

    raise forms.ValidationError("Passwords must match!")