扩展Django的用户模型不会填充auth.user

时间:2015-10-23 15:18:56

标签: django django-authentication

所以,我扩展了Django的用户模型(见https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#specifying-a-custom-user-model)。

以下是我的模特:

class User(AbstractBaseUser):
    email = models.EmailField(verbose_name = 'email address',unique = True, db_index = True)

    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 30)
    joined = models.DateTimeField(auto_now_add = True)
    is_active = models.BooleanField(default = True)
    is_admin = models.BooleanField(default = False)
    ...

    USERNAME_FIELD = 'email' 

在报名表中:

class RegistrationForm(forms.ModelForm):
    """
    Form for registering a new account
    """

    email = forms.EmailField(widget = forms.widgets.TextInput,
                             label = 'Email',
                             )
    password1 = forms.CharField(widget = forms.widgets.PasswordInput,
                               label = 'password'
                               )
    password2 = forms.CharField(widget = forms.widgets.PasswordInput,
                                label = 'password (again)'
                                )


    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'password1', 'password2', 'user_type']

    ...

    def save(self, commit = True):

        user = super(RegistrationForm, self).save(commit = False)

        the_password = self.cleaned_data['password1']

        user.set_password(the_password) # This Hashes the password before saving it

        if commit:
            user.save()            
            return user

最后,在views.py中:

class Registration(View):
    signup_form = RegistrationForm
    template_name = 'accounts/signup.html'

    def post(self, request):
        the_signup_form = self.signup_form(request.POST if any(request.POST) else None)
        ...
        if the_signup_form.is_valid():
            cleaned_signup_form = the_signup_form.cleaned_data
            the_user = the_signup_form.save()  # User is saved. 
            return redirect('/')

现在,问题是在提交表单后,自定义用户模型的表格填写得很好,但是Django" auth_user"表不是!我认为调用 user = super(RegistrationForm,self).save(commit = False)将负责保存到基础类。当然,当我尝试进行身份验证时:

this_user = authenticate(email = the_user.email,
                         password = the_user.password)

this_user为None,因此不会登录用户。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

AbstractBaseUserabstract base class,没有为其创建表格。

当您在设置中设置AUTH_USER_MODEL = 'myapp.MyUser'时,User模型将被用作<{1}}模型的 ,因此您不应拥有django.contrib.auth.models.User模型{1}}表格。

当您致电auth_user时,会调用父类super(RegistrationForm, self).save(commit=False)的保存方法,它与ModelForm模型无关。

答案 1 :(得分:0)

AbstractBaseUser扩展,您会得到类似于内置User模型类的内容。

从您提供的链接:

  

AbstractBaseUser提供了User模型的核心实现,   包括散列密码和标记化密码重置。

因此,您实际上并未使用django.contrib.auth.models.User,您可以随时从django.contrib.auth.models.User扩展以添加一些属性,或创建新模型并使用1链接到django的User模型:1关系。