Tạo và tùy chỉnh User Model trong Django sử dụng Django Abstractuser
Có nhiều cách để tạo và tùy chỉnh User Model trong Django nhưng mình sử dụng Django Abstractuser vì nó có thể loại bỏ các trường không cần thiết trong Model. Ví dụ mặc định Django sử dụng username và password để xác thực nhưng mình muốn bỏ trường này và dùng email để xác thực. Khi không dùng nữa thì mình muốn bỏ luôn trường này trong Model
Tạo và tùy chỉnh User Model
Edit file models.py trong thư mục users
from django.db import models
from django.contrib.auth.models import AbstractUser
from .managers import CustomUserManager
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Users(AbstractUser):
username = None
email = models.EmailField(_('email address'), max_length=50, unique=True)
birthday = models.DateField(null=True, blank=True)
address = models.CharField(max_length=500, blank=True)
phone = models.CharField(max_length=10, blank=True)
facebook = models.CharField(max_length=500, blank=True)
is_seller = models.BooleanField(default=False)
is_buyer = models.BooleanField(default= True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
Tạo model users với các trường mới mà mặc định không có như phone, facebook… Ngoài ra username = none là xóa trường này trong model vì ta không dùng tới nữa. Gán lại USERNAME_FIELD = ’email’ để dùng email thay cho username. REQUIRED_FIELDS = [] dùng để thêm trường bắt buộc khi tạo tài khoản mới.
Tùy chỉnh thông tin hiển thị
Edit file admin.py trong thư mục users
from django.contrib import admin
from django.db import models
from users.models import Users
from users.froms import UsersCreationFrom
from django.contrib.auth.admin import UserAdmin
# Register your models here.
class UsersAdmin(UserAdmin):
model = Users
add_form = UsersCreationFrom
list_display = ('email', 'first_name', 'last_name', 'is_staff')
ordering = ('email',)
search_fields = ('email',)
fieldsets = (
(
'User profile',
{
'fields': (
'first_name',
'last_name',
'email',
'password',
'date_joined',
'last_login',
'birthday',
'address',
'phone',
'facebook',
)
}
),
(
'User role',
{
'fields': (
'is_seller',
'is_buyer',
'is_staff',
'is_superuser',
'is_active',
)
}
)
)
add_fieldsets = (
None,
{
'fields': (
'email',
'password1',
'password2',
)
}
),
admin.site.register(Users, UsersAdmin)
list_display tùy chỉnh hiển thị các trường trong danh sách user
fieldsets tùy chỉnh các trường hiển thị các giá trị của từng user
Tạo file managers.py trong thưu mục users với nội dung như sau để thực hiện việc tạo user và superuser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email 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, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
Tạo file froms.py trong thư mục users với nội dung sau
from django import forms
from django.contrib.auth.forms import UserCreationForm
from users.models import Users
class UsersCreationFrom(UserCreationForm):
class Meta:
model = Users
fields = ['email', 'password', 'password1']
Khai báo app users
Trong file settings.py trong thư mục webApp thêm các dòng cấu hình sau
Thêm app users vào INSTALLED_APPS và thêm AUTH_USER_MODEL = ‘users.Users’
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users',
]
AUTH_USER_MODEL = 'users.Users'
chạy các lệnh sau để apply model xuống database.
manage.py makemigrations
manage.py migrate
(venv) C:\Users\Hugo\Desktop\quanlydon>manage.py createsuperuser
Email address: [email protected]
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
(venv) C:\Users\Hugo\Desktop\quanlydon>
Cảnh báo do để pass không bảo mật. Mình test nên để tạm cho dễ input. Giờ runserver phát xem nào
(venv) C:\Users\Hugo\Desktop\quanlydon>manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
August 24, 2021 - 21:31:49
Django version 3.2.6, using settings 'webApp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
OK rồi. Giờ sang bước tiếp theo, dùng templates để tùy chỉnh giao diện của web