搜索

首页  >  问答  >  正文

python - django扩展AbstractBaseUser,并且自定义了用户ID,进入admin后台,添加新用户时报错?

代码:

# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin)
import uuid
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# Create your models here.

class MyUserManager(BaseUserManager):
    def create_user(self, mobile, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not mobile:
            raise ValueError('Users must have an mobile')
        user = self.model(
            mobile = mobile,
        )
        user.id = uuid.uuid3(uuid.NAMESPACE_DNS, str(mobile))
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self,mobile,password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(mobile,
                                password=password,
                                )
        user.is_staff=True
        user.is_superuser=True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser, PermissionsMixin):
    id = models.CharField(
         verbose_name='用户ID', max_length=40, unique=True, primary_key=True
     )
    mobile = models.CharField(
        verbose_name='手机号', max_length=11, unique=True
    )
    is_staff = models.BooleanField(verbose_name='staff status', default=False)
    is_active = models.BooleanField(verbose_name='active', default=True)
    date_joined = models.DateTimeField(verbose_name='注册时间', blank=True, null=True)

    object = MyUserManager()

    USERNAME_FIELD = 'mobile'
    # REQUIRED_FIELDS = ['date_of_birth']
    REQUIRED_FIELDS = []

    def get_full_name(self):
        # The user is identified by their email address
        return self.mobile

    def get_short_name(self):
        # The user is identified by their email address
        return self.mobile

    def __unicode__(self):
        return "{0}, {1}".format(self.id, self.mobile)

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

当不使用自定义的ID时是正常的,自定义ID之后,添加新用户就出错,求教!

阿神阿神2785 天前689

全部回复(0)我来回复

暂无回复
  • 取消回复