确定用户是否在Django中是成人

时间:2015-01-25 21:37:51

标签: django python-datetime django-custom-user

我正在尝试使用他的生日和今天的日期确定我网站上的用户是否是成年人。

我的用户名为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

当我在添加“成人生日”后检查我的管理页面时,结果始终为false。

我在表单或set_adult方法中犯了错误吗?

1 个答案:

答案 0 :(得分:2)

    user.set_adult # NOT WORKING

您在函数调用中缺少()

    user.set_adult()