創(chuàng)建Django的用戶注冊和登錄
python manage.py startapp authentication
創(chuàng)建一個用于用戶的APP應(yīng)用
manager是Django提供數(shù)據(jù)庫查詢操作的接口情妖,自定義manager可以實現(xiàn)想要的任何數(shù)據(jù)操作处硬。
通過繼承BaseUserManger類谐宙,實現(xiàn)兩個方法
create_user(): 創(chuàng)建普通用戶
create_superuser(): 創(chuàng)建超級用戶
from django.contrib.auth.models import BaseUserManager
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, username, email, password, **kwargs):
'''
創(chuàng)建用戶
'''
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):
"""
創(chuàng)建超級管理用戶
"""
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: 注冊的用戶應(yīng)用,其中需要確保APP已經(jīng)在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'