Django子类(模型)没有实现超类的属性

时间:2014-03-13 10:09:22

标签: python django

我为我的网站用户创建了一个模型:

class ImrayWebsiteUser(models.Model):
    user = models.OneToOneField(User) 
    score = models.IntegerField(default=0)   
    birthDate = models.DateField(null=True,blank=True)
    clubs = models.ManyToManyField(Club)

在视图中,我为新用户创建了一个页面进行注册。当他们点击注册(填写表格后)后,我创建了另一个视图,用于检查表单并保存用户数据(如果有效)。

这是观点:

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save() #save user registeration data
            return HttpResponseRedirect('/accounts/register_success') 

    # in the first time it generate empty form:
    args = {}
    args.update(csrf(request))

    args['form'] = MyRegistrationForm()

    return render_to_response('accounts/register.html', args)

形式:

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=False,max_length=30)
    last_name = forms.CharField(required=False,max_length=30)

    class Meta:
        model = ImrayWebsiteUser
        fields = ('username', 'email', 'password1', 'password2',
                  'first_name', 'last_name')

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.firstname = self.cleaned_data['first_name']
        user.lastname = self.cleaned_data['last_name']
        # user.set_password(self.cleaned_data['password1'])

        if commit:
            user.save()

        return user

问题,当我填写表单信息,然后点击注册(从而执行查看并将数据发送到表单)时,我得到一个AttributeError说{{ 1}}没有名为ImrayWebsiteUser的属性。但这不应该发生,因为我的用户set_password清楚地实现了内置的用户类型。

这是错误代码:

ImrayWebsiteUser

1 个答案:

答案 0 :(得分:1)

您的OnetoOneField未实施用户模型。

https://docs.djangoproject.com/en/1.6/ref/models/fields/#ref-onetoone

您可以在案例中访问OneToOneField object.user属性。

由于您使用的是实现UserCreationForm的内置set_password,因此您可以在模型中创建名为set_password的方法并调用self.user.set_password

但我建议您研究自定义用户实现:

https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#auth-custom-user

编辑: 根据我的问题,这只是一个概念:

class UserProfile(models.Model):
  user = models.OneToOneField(User)
  .....your other attributes

对于RegistrationForm,您可以执行以下操作:

class MyRegistrationForm(UserCreationForm):
  ....your registration form attributes from UserProfile Model
  class Meta:
    fields = ('username', 'email', 'firstname', 'lastname')  # fields of User Model not your UserProfile Model

  def save(self, commit=True):
     user = super(MyRegistrationForm, self).save(commit=commit)
     userprofile = UserProfile(user=user)
     userprofile.attribute = form.cleaned_data[attribute_name]...
     return user|userprofile #as required

csrf模板中已经提供{%csrf_token%}