1.AbstractUser
If you want to create a user, you need to set various fields, groups, permissions, cookie management, password handling, etc., which is more troublesome, so Django has created an abstract user for us, we only need to inherit it, and then add our own fields.
Basic user attributes and common methods
Attribute or method | Description |
---|---|
username | Username (required) |
password | Password (required) |
first_name | first name |
last_name | Last name |
is_staff | Whether the administrator |
create() | Create a normal user |
create_user() | Create an ordinary user, password encryption |
create_superuser() | Create a super user (email necessary) |
set_password(pwd) | set password |
To create a user, import the User in the authentication model class, and then use the User object to create the user
from django.contrib.auth.models import User
User.objects.create(username='laowang',password='123')
2. Custom user model class (inherited Abstract)
Obviously Django's own user model class User cannot meet our needs. For example, we also need to add other custom fields such as mobile phone number, whether to remember the password, etc., so we can customize the model class and then inherit Abstract
Here in the users.models.py file, define a class User and add the mobile phone number field
from django.db import models
from django.contrib.auth.models import AbstractUser
# 继承AbstractUser
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
class Meta:
db_table = 'tb_users'
verbose_name = '用户'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
3. Specify the user model class
We need to configure to use the custom model class,' application name.User ',
open the project configuration file (here is dev.py)
# AUTH_USER_MODEL = 'auth.User' 这是系统默认值
AUTH_USER_MODEL = 'users.User'
4. Data migration
The data table is generated when the data migration is completed (the configuration of the Django database is ignored here)
python manage.py makemigrations
python manage.py migrate
5. Create user
# 导入自定义的模型类(继承Abstract那个)
from apps.users.models import User
try:
user = User.objects.create_user(username="laowang",password="123456",mobile="10086")
except Exception as e:
pass