django 扩展user
时间: 2023-11-04 22:05:02 浏览: 71
Python库 | django-user-0.0.6.tar.bz2
Django中有一个内置的User模型,但是如果需要添加一些额外的字段或方法,可以通过扩展User模型来实现。
方法1:使用AbstractBaseUser和BaseUserManager
可以通过继承AbstractBaseUser和BaseUserManager来创建自定义User模型,具体步骤如下:
1. 创建一个新的app
```
python manage.py startapp accounts
```
2. 在models.py中创建自定义User模型
```python
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
name = models.CharField(max_length=30, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
```
3. 修改setting.py中的AUTH_USER_MODEL
```python
AUTH_USER_MODEL = 'accounts.CustomUser'
```
4. 执行数据库迁移
```
python manage.py makemigrations
python manage.py migrate
```
5. 创建超级用户
```
python manage.py createsuperuser
```
方法2:使用AbstractUser
Django还提供了一个AbstractUser模型,可以通过继承该模型来扩展User模型。
具体步骤如下:
1. 创建一个新的app
```
python manage.py startapp accounts
```
2. 在models.py中创建自定义User模型
```python
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
name = models.CharField(max_length=30, blank=True)
```
3. 修改setting.py中的AUTH_USER_MODEL
```python
AUTH_USER_MODEL = 'accounts.CustomUser'
```
4. 执行数据库迁移
```
python manage.py makemigrations
python manage.py migrate
```
5. 创建超级用户
```
python manage.py createsuperuser
```
阅读全文