Django Custom User未登录

时间:2016-03-19 11:54:50

标签: python django django-custom-user

我在Django 1.9中从AbstractUser创建了一个CustomUser。添加admin.sites.register当我创建超级用户时,django已经创建成功,但是当我登录系统时,用户并不存在。 请遵循以下代码:

customuser/models.py

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


class CustomUserManager(BaseUserManager):
    def create_user(self, username, email, first_name, last_name, cpf, password=None):
        user = self.model(
            username=username,
            email=email,
            first_name=first_name,
            last_name=last_name,
            cpf=cpf
        )
        return user

    def create_superuser(self, username, email, first_name, last_name, cpf, password):
        user = self.create_user(username, email, first_name, last_name, cpf,
                                password=password)
        user.is_super_user = True
        user.save()
        return user


class CustomUser(AbstractUser):

    SEXO_CHOICES = (
        (u'Masculino', u'Masculino'),
        (u'Feminino', u'Feminino'),
    )

    cpf = models.BigIntegerField(unique=True)
    phone = models.CharField(max_length=15, blank=True)
    is_super_user = models.BooleanField(default=False)
    data_de_nascimento = models.DateField(null=True)
    sexo = models.CharField(max_length=9, null=True, choices=SEXO_CHOICES)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'cpf']
objects = CustomUserManager()

settins.py上,我添加以下行:

INSTALLED_APPS = [
   ...
   'customuser',
]

...

AUTH_USER_MODEL = 'customuser.CustomUser'

我的customuser/admin.py

from django.contrib import admin

from models import CustomUser, CustomUserManager


admin.site.register(CustomUser)

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

See these docs让自定义用户使用管理网站。

<强>更新

抱歉,以前我想过,你是从AbstractBaseUser继承了你的模型,因此答案给你错误。

由于您继承自AbstractUser,您的子类将自动获得is_staff字段。因此,您只需要在is_staff方法中将True设置为create_superuser

class CustomUserManager(...):
    # ...

    def create_superuser(...):
        # ...
        user.is_staff = True
        user.save()
        return user