创建Django的用户注册和登录
python manage.py startapp authentication
创建一个用于用户的APP应用
manager是Django提供数据库查询操作的接口,自定义manager可以实现想要的任何数据操作。
通过继承BaseUserManger类,实现两个方法
create_user(): 创建普通用户
create_superuser(): 创建超级用户
from django.contrib.auth.models import BaseUserManager
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, username, email, password, **kwargs):
'''
创建用户
'''
if not email:
raise ValueError("Users must have avalid email!!")
user = self.model(
username = username,
email = self.normalize_email(email),
)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password, **kwargs):
"""
创建超级管理用户
"""
user = self.create_user(username, email, password)
user.is_admin = True
user.is_superuser = True
user.is_staff = True
user.save()
return user
编辑用户的model
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .manager import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=100, unique=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', ]
class Meta():
verbose_name = 'user'
verbose_name_plural = 'users'
def get_userid(self):
return User.objects.get(username=self.username).user_id
在settings配置中配置使用重写的User
AUTH_USER_MODEL = 'app.youruser'
app: 注册的用户应用,其中需要确保APP已经在installed_apps中添加了
youruser: 是重写的User模型
HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'.
解决办法: AUTH_USER_MODEL = '项目名称.User'
网友评论