1

我试图通过使用他的生日和今天的日期来确定我网站上的用户是否是成年人。

我的用户中有一个布尔属性,adult我尝试通过以下方式设置它

from datetime import date

...

def set_adult(self):
    today = date.today()
    age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
    if age > 18:
      self.adult = True
    else:
      self.adult = False

注册用户时,我有一个添加生日的字段

class MyRegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    email = forms.EmailField(widget=forms.EmailInput,label="Email")
    date_of_birth = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y'), label="Date of birth (MM/DD/YYYY)")
    gender = forms.ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES)
    password1 = forms.CharField(widget=forms.PasswordInput,
                                label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,
                                label="Password (again)")

    class Meta:
        model = MyUser
        fields = ['email', 'date_of_birth', 'gender', 'password1', 'password2']

    def clean(self):
        """
        Verifies that the values entered into the password fields match

        NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
        """
        cleaned_data = super(MyRegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user.set_adult # NOT WORKING
        if commit:
            user.save()
        return user

当我在添加“成人生日”后检查我的管理页面时,结果总是错误的。

我的形式或set_adult方法有误吗?

4

1 回答 1

3
    user.set_adult # NOT WORKING

()在函数调用中缺少:

    user.set_adult()
于 2015-01-25T21:42:21.327 回答