Python Django - form.is_valid()一直抛出没有属性的unicode对象get错误



我正在创建一个自定义用户类型的表单。但是每次我提交表单来测试它时,它都会返回一个错误,说unicode对象没有属性get error。

forms.py:

class RegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    password1 = forms.CharField(widget=forms.PasswordInput,
                                label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,
                                label="Password (again)")
    class Meta:
        model = Student
        fields = ('firstname', 'lastname', 'email', 'password1', 'password2', 'is_second_year')
    def clean(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

models.py:

class StudentManager(BaseUserManager):
    def create_user(self, firstname, lastname, email, is_second_year, password, is_officer=False, hours=0, points=0):
        if not email:
            raise ValueError("Student must have an email address.")
        newStudent = self.model(
            email = self.normalize_email(email),
            firstname=firstname,
            lastname=lastname,
            is_officer=is_officer,
            is_second_year=is_second_year,
            hours=hours,
            points=points
        )
        newStudent.set_password(password)
        user.save(using=self.db)
        return newStudent
    def create_superuser(self, firstname, lastname, email, password, is_second_year, is_officer=True, hours=0, points=0):
        newSuperStudent = self.create_user(
            email = self.normalize_email(email),
            firstname=firstname,
            lastname=lastname,
            is_officer=is_officer,
            is_second_year=is_second_year,
            hours=hours,
            points=points,
            password=password
        )
        newSuperStudent.is_admin = True
        newSuperStudent.save(using=self.db)
        return newSuperStudent

class Student(AbstractBaseUser):
    firstname = models.CharField(verbose_name="First Name", max_length=30, default="")
    lastname = models.CharField(verbose_name="Last Name", max_length=30, default="")
    email = models.EmailField(
        verbose_name='Email Address',
        max_length=255,
        unique=True,
        default=''
    )
    is_officer = models.BooleanField(default=False)
    is_second_year = models.BooleanField(verbose_name="Check this box if this is your second year in NHS")
    hours = models.DecimalField(max_digits=5, decimal_places=2)
    points = models.DecimalField(max_digits=3, decimal_places=1)
    USERNAME_FIELD = 'email'
    def __unicode__(self):
        return self.username

views.py:

def sign_up(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = RegistrationForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            print "money"
            form.save()
            # redirect to a new URL:
            return HttpResponseRedirect('/sign_up_success/')
    # if a GET (or any other method) we'll create a blank form
    args = {}
    args.update(csrf(request))
    args['form'] = RegistrationForm()
    return render_to_response('events/sign_up.html', args)

.is_valid()方法中的错误位置:

 field_value = self.cleaned_data.get(field, None)

我的猜测是,出于某种原因,我的表单的cleaned_data属性是一个unicode对象,而不是一个字典。但我不知道为什么会这样!

clean必须返回完整的cleaned_data字典,而不是单个字符串字段。

最新更新