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

查看:867
本文介绍了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之后,添加新用户就出错,求教!

解决方案

uuid不是整数,要使用uuid作为主键,需要在自定义用户模型中的id字段设置为主键,

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text='id')

这篇关于python - django扩展AbstractBaseUser,并且自定义了用户ID,进入admin后台,添加新用户时报错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆