Theo quan điểm của bạn. py
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from decouple import config
from django.contrib.auth import authenticate
import jwt
@api_view[['POST']]
@permission_classes[[AllowAny]]
def get_tokens_for_user[request]:
username = request.POST.get["username"]
password = request.POST.get["password"]
user = authenticate[username=username, password=password];
if user is not None:
refreshToken = RefreshToken.for_user[user]
accessToken = refreshToken.access_token
decodeJTW = jwt.decode[str[accessToken], config['SECRET_KEY'], algorithms=["HS256"]];
# add payload here!!
decodeJTW['iat'] = '1590917498'
decodeJTW['user'] = 'tiago'
decodeJTW['date'] = '2020-05-31'
#encode
encoded = jwt.encode[decodeJTW, config['SECRET_KEY'], algorithm="HS256"]
return Response[{
'status': True,
'refresh': str[refreshToken],
'access': str[encoded],
}]
else:
return Response[{
'status': False
}]
# No backend authenticated the credentials
Trong url của bạn. py
from django.urls import path, include
from .views import get_tokens_for_user
urlpatterns = [
path['login/', get_tokens_for_user, name="login"],
]
Trong cài đặt của bạn. py
from pathlib import Path
from datetime import timedelta
from decouple import config
...
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config['SECRET_KEY']
# Application definition
INSTALLED_APPS = [
...
# Rest
'rest_framework',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
# JWT
# //django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta[minutes=60],
'REFRESH_TOKEN_LIFETIME': timedelta[days=1],
'AUTH_HEADER_TYPES': ['Bearer',],
'SIGNING_KEY': config['SECRET_KEY'],
'VERIFYING_KEY': config['SECRET_KEY'],
'ALGORITHM': 'HS256',
}
Trong thư mục gốc của bạn thêm. env
SECRET_KEY = 'ep@4ojr4m!h73y2j[stackoverflow]kra1*@tq$5el626wf@&p60]7u!6552+-'
Giá trị thời gian chạy
decodeJTW = {
'token_type': 'access',
'exp': 1612651527,
'jti': '7f415b28610348468ce74ec0f480fad1',
'user_id': 2,
'iat': '1590917498',
'user': 'tiago',
'date': '2020-05-31'
}
encode = {
"status":true,
"refresh":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMjczNDU0NywianRpIjoiMDQ0MDI3ZTQzMTc2NDFiNDhhOGI2MjU4MjE4ZGZjNDkiLCJ1c2VyX2lkIjoyfQ.Qf0YfJLAmdYuavDHVng7Bwjmka551G6c1Gi4e-UdRuc",
"access":"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjEyNjUxNzQ3LCJqdGkiOiI2OWEzNjYwYjYxMTk0MzVjYjljZTA0OGQ3MmE1ODk1YSIsInVzZXJfaWQiOjIsImlhdCI6IjE1OTA5MTc0OTgiLCJ1c2VyIjoidGlhZ28iLCJkYXRlIjoiMjAyMC0wNS0zMSJ9.XUMvhL13zDZdbjYYPkYnwlZoHN6U7Zc3xUzXsKoVj2I'"
}
Django đi kèm với một hệ thống xác thực dựa trên phiên hoạt động vượt trội. Nó bao gồm tất cả các mô hình, chế độ xem và mẫu bạn cần để cho phép người dùng đăng nhập và tạo tài khoản mới. Đây là chà mặc dù. Xác thực của Django chỉ hoạt động với chu trình phản hồi yêu cầu HTML truyền thống
Ý nghĩa của "chu trình phản hồi yêu cầu HTML truyền thống" là gì? . Khi họ nhấp vào nút "Gửi", trình duyệt sẽ đưa ra yêu cầu — bao gồm dữ liệu mà người dùng đã nhập vào biểu mẫu đăng ký — đến máy chủ, máy chủ sẽ xử lý yêu cầu đó và sẽ phản hồi bằng HTML hoặc chuyển hướng trình duyệt . Đây là điều chúng tôi muốn nói khi nói về việc thực hiện "làm mới toàn trang. "
Tại sao biết rằng xác thực tích hợp của Django chỉ hoạt động với chu trình phản hồi yêu cầu HTML truyền thống lại quan trọng? . Thay vào đó, máy khách mong muốn máy chủ trả về JSON thay vì HTML. Bằng cách trả về JSON, chúng tôi có thể để máy khách quyết định nên làm gì tiếp theo thay vì để máy chủ quyết định. Với chu kỳ phản hồi yêu cầu JSON, máy chủ nhận dữ liệu, xử lý dữ liệu và trả về phản hồi [giống như trong chu kỳ phản hồi yêu cầu HTML], nhưng phản hồi không kiểm soát hành vi của trình duyệt. Nó chỉ cho chúng ta biết kết quả của yêu cầu
May mắn thay, nhóm đằng sau Django đã nhận ra rằng xu hướng phát triển web đang đi theo hướng này. Họ cũng biết rằng một số dự án có thể không muốn sử dụng các mô hình, dạng xem và mẫu tích hợp sẵn. Thay vào đó, họ có thể chọn sử dụng các phiên bản tùy chỉnh. Để đảm bảo tất cả những nỗ lực xây dựng hệ thống xác thực tích hợp của Django không bị lãng phí, họ đã quyết định làm cho nó có thể sử dụng những phần quan trọng nhất trong khi vẫn duy trì khả năng tùy chỉnh kết quả cuối cùng
Chúng ta sẽ đi sâu vào vấn đề này sau trong chương. Bây giờ, đây là những gì bạn muốn biết
- Chúng tôi sẽ tạo mô hình
6 của riêng mình để thay thế mô hình của Django# Tell Django about the custom `User` model we created. The string # `authentication.User` tells Django we are referring to the `User` model in # the `authentication` module. This module is registered above in a setting # called `INSTALLED_APPS`. AUTH_USER_MODEL = 'authentication.User'
- Chúng tôi sẽ phải viết các chế độ xem của mình để hỗ trợ trả về JSON thay vì HTML
- Bởi vì chúng tôi sẽ không sử dụng HTML, chúng tôi không cần các mẫu đăng nhập và đăng nhập tích hợp của Django
Nếu bạn đang tự hỏi những gì còn lại để chúng tôi sử dụng, đó là một câu hỏi công bằng. Điều này quay trở lại với những gì chúng ta đã nói trước đó về Django cho phép sử dụng các phần cốt lõi của xác thực mà không cần sử dụng hệ thống xác thực mặc định
Theo mặc định, Django sử dụng phiên để xác thực. Trước khi tiếp tục, chúng ta nên nói về ý nghĩa của điều này, tại sao nó lại quan trọng, xác thực dựa trên mã thông báo và Mã thông báo web JSON [viết tắt là JWT] là gì và chúng ta sẽ sử dụng mã nào trong khóa học này
Trong Django, các phiên được lưu trữ dưới dạng cookie. Các phiên này, cùng với một số đối tượng yêu cầu và phần mềm trung gian được tích hợp sẵn, đảm bảo rằng luôn có người dùng sẵn sàng cho mọi yêu cầu. Người dùng có thể được truy cập dưới dạng
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
7. Khi người dùng đăng nhập, # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
7 là một thể hiện của lớp # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6. Khi họ đăng xuất, # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
7 là một thể hiện của lớp python manage.py makemigrations
1. Cho dù người dùng có được xác thực hay không, thì # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
7 sẽ luôn tồn tạiCó gì khác biệt? . Nếu
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
7 là một phiên bản của python manage.py makemigrations
1, thì python manage.py makemigrations
3 sẽ luôn trả về python manage.py makemigrations
5. Điều này cho phép nhà phát triển [bạn. ] để biến python manage.py makemigrations authentication
0 thành python manage.py makemigrations authentication
1. Gõ ít hơn là một điều tốt trong trường hợp nàyTrong trường hợp của chúng tôi, máy khách và máy chủ sẽ chạy ở các vị trí khác nhau. Máy chủ sẽ chạy lúc
python manage.py makemigrations authentication
2 và máy khách sẽ chạy lúc python manage.py makemigrations authentication
3. Trình duyệt coi hai vị trí này nằm trên các miền khác nhau, tương tự như chạy máy chủ trên python manage.py makemigrations authentication
4 và chạy ứng dụng khách trên python manage.py makemigrations authentication
5. Chúng tôi sẽ không cho phép các miền bên ngoài truy cập vào cookie của chúng tôi, vì vậy chúng tôi phải tìm một giải pháp thay thế khác để sử dụng phiênNếu bạn thắc mắc tại sao chúng tôi không cho phép truy cập vào cookie của mình, thì bạn nên xem các bài viết về Chia sẻ tài nguyên trên nhiều nguồn gốc [CORS] và Giả mạo yêu cầu trên nhiều trang web [CSRF] được liên kết bên dưới. Nếu bạn chỉ muốn bắt đầu viết mã, hãy đánh dấu vào các ô và tiếp tục
Giải pháp thay thế phổ biến nhất cho xác thực dựa trên phiên là xác thực dựa trên mã thông báo và chúng tôi sẽ sử dụng một hình thức xác thực dựa trên mã thông báo cụ thể để bảo mật ứng dụng của chúng tôi
Với xác thực dựa trên mã thông báo, máy chủ cung cấp cho khách hàng mã thông báo khi yêu cầu đăng nhập thành công. Mã thông báo này là duy nhất cho người dùng đăng nhập và được lưu trữ trong cơ sở dữ liệu cùng với ID của người dùng. Khách hàng dự kiến sẽ gửi mã thông báo với các yêu cầu trong tương lai để máy chủ có thể xác định người dùng. Máy chủ thực hiện việc này bằng cách tìm kiếm bảng cơ sở dữ liệu chứa tất cả các mã thông báo đã được tạo. Nếu tìm thấy mã thông báo phù hợp, máy chủ sẽ tiếp tục xác minh rằng mã thông báo vẫn hợp lệ. Nếu không tìm thấy mã thông báo phù hợp, thì chúng tôi nói rằng người dùng chưa được xác thực
Vì mã thông báo được lưu trữ trong cơ sở dữ liệu chứ không phải trong cookie nên xác thực dựa trên mã thông báo sẽ phù hợp với nhu cầu của chúng tôi
Đang xác minh mã thông báo
Chúng tôi luôn có tùy chọn lưu trữ nhiều hơn chỉ ID của người dùng với mã thông báo của họ. Chúng tôi cũng có thể lưu trữ những thứ như ngày mà mã thông báo sẽ hết hạn. Trong ví dụ này, chúng tôi cần đảm bảo rằng thời hạn này chưa qua. Nếu có, thì mã thông báo không hợp lệ. Vì vậy, chúng tôi xóa nó khỏi cơ sở dữ liệu và yêu cầu người dùng đăng nhập lại
Mã thông báo web JSON
Mã thông báo web JSON [viết tắt là JWT] là một tiêu chuẩn mở [RFC 7519] xác định một cách nhỏ gọn và khép kín để truyền thông tin an toàn giữa hai bên. Bạn có thể coi JWT là mã thông báo xác thực trên steroid
Bạn có nhớ khi tôi nói rằng chúng tôi sẽ sử dụng một hình thức xác thực dựa trên mã thông báo cụ thể không?
Tại sao Mã thông báo web JSON tốt hơn mã thông báo thông thường?
Có một vài lợi ích chúng tôi nhận được khi sử dụng JWT so với mã thông báo thông thường
- JWT là một tiêu chuẩn mở. Điều đó có nghĩa là tất cả các triển khai của JWT phải khá giống nhau, đây là một lợi ích khi làm việc với các ngôn ngữ và công nghệ khác nhau. Mã thông báo thông thường có dạng tự do hơn, cho phép nhà phát triển quyết định cách tốt nhất để triển khai mã thông báo
- JWT có thể chứa tất cả thông tin về người dùng, thuận tiện cho khách hàng
- Thư viện xử lý việc nâng hạng nặng ở đây. Việc triển khai xác thực của riêng bạn rất nguy hiểm, vì vậy chúng tôi để lại những nội dung quan trọng cho các thư viện đã được thử nghiệm thực tế mà chúng tôi có thể tin tưởng
Tạo mô hình Người dùng
Làm thế nào về chúng ta bắt đầu?
Tệp
python manage.py makemigrations authentication
6 lưu trữ các mô hình chúng tôi sẽ sử dụng để xác thực. Nếu bạn sao chép kho lưu trữ trước đó trong khóa học, bạn sẽ nhận thấy rằng thư mục python manage.py makemigrations authentication
7 đã tồn tại. Tuy nhiên, tệp python manage.py makemigrations authentication
8 không. Bạn sẽ muốn tự tạo tệp nàyGiải thích của chúng tôi về mã trong suốt khóa học này là cố ý ngắn. Giữa các nhận xét trong mã và các tài nguyên mà chúng tôi liên kết đến, chúng tôi tin rằng bạn có thể tìm thấy thông tin mình cần
Tạo
python manage.py makemigrations authentication
6Chúng tôi sẽ cần các lần nhập sau để tạo các lớp
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 và python manage.py createsuperuser
1, vì vậy hãy tiếp tục và thêm phần sau vào đầu tệpimport jwt
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.models import [
AbstractBaseUser, BaseUserManager, PermissionsMixin
]
from django.db import models
Khi tùy chỉnh xác thực trong Django, một yêu cầu là bạn chỉ định một lớp
python manage.py createsuperuser
2 tùy chỉnh với hai phương thức. python manage.py createsuperuser
3 và python manage.py createsuperuser
4. Để tìm hiểu về xác thực tùy chỉnh trong Django, hãy đọcHãy bắt đầu bằng cách tạo lớp
python manage.py createsuperuser
1Nhập mã cho lớp
python manage.py createsuperuser
1 vào python manage.py makemigrations authentication
6 và ghi chú các nhận xétĐọc Người quản lý để tìm hiểu những gì một lớp học
2 làmpython manage.py createsuperuser
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
Bây giờ chúng ta có lớp người quản lý, chúng ta có thể tạo mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6Thêm mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 vào dưới cùng của python manage.py makemigrations authentication
6class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
Lướt qua đoạn mã trên trong vài phút rồi làm như sau
Nếu bạn muốn biết thêm về xác thực tùy chỉnh trong Django, tài liệu là một nơi tuyệt vời để tìm hiểu. Các liên kết sau đây là tùy chọn, nhưng chúng tôi khuyên bạn nên xem chúng nếu quan tâm
Chỉ định cài đặt AUTH_USER_MODEL
Theo mặc định, Django giả định rằng mô hình người dùng là
python manage.py shell_plus
2. Tuy nhiên, chúng tôi muốn sử dụng # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 tùy chỉnh của riêng mình. Vì chúng ta đã tạo lớp # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6, điều tiếp theo chúng ta cần làm là yêu cầu Django sử dụng mô hình # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 của chúng ta thay vì sử dụng mô hình của chính nó.Chúng tôi khuyên bạn nên dành một giây để đọc;
Nếu bạn đã di chuyển cơ sở dữ liệu của mình trước khi chỉ định mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 tùy chỉnh, bạn có thể cần xóa cơ sở dữ liệu của mình và chạy lại quá trình di chuyển của mìnhNói với Django về mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 của chúng tôi bằng cách chỉ định cài đặt python manage.py shell_plus
8 trong python manage.py shell_plus
9Để đặt cài đặt
python manage.py shell_plus
8, hãy nhập thông tin sau vào cuối python manage.py shell_plus
9# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
Tạo và chạy di chuyển
Khi chúng tôi thêm các mô hình mới và thay đổi các mô hình hiện có, chúng tôi sẽ cần cập nhật cơ sở dữ liệu để phản ánh những thay đổi này. Di chuyển là những gì Django sử dụng để thông báo cho cơ sở dữ liệu rằng có điều gì đó đã thay đổi và cơ sở dữ liệu của chúng tôi sẽ thông báo cho cơ sở dữ liệu rằng chúng tôi cần thêm một bảng mới cho mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 tùy chỉnh của mình**Ghi chú. **Nếu bạn đã chạy
>>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
3 hoặc >>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
4, bạn sẽ cần xóa cơ sở dữ liệu của mình trước khi tiếp tục. Nếu bạn đang sử dụng SQLite làm cơ sở dữ liệu, thì tất cả những gì bạn cần làm là xóa tệp có tên >>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
5 trong thư mục gốc của dự án của bạnNếu bạn đang sử dụng PostgreSQL, hãy làm theo hướng dẫn bên dưới
Nếu bạn đã chạy
>>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
3 hoặc >>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
4 rồi, vui lòng xóa tệp >>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
5 khỏi thư mục gốc của dự án của bạn. Django sẽ không hài lòng nếu bạn thay đổi python manage.py shell_plus
8 sau khi tạo cơ sở dữ liệu và tốt nhất là bỏ cơ sở dữ liệu và bắt đầu lạiBây giờ bạn đã sẵn sàng để tạo và áp dụng di chuyển. Sau đó, chúng ta có thể tạo người dùng đầu tiên của mình
Để tạo di chuyển, bạn cần chạy lệnh sau trong bảng điều khiển của mình để tạo di chuyển
python manage.py makemigrations
Điều này tạo ra các di chuyển mặc định cho dự án Django mới của chúng tôi. Tuy nhiên, nó sẽ không tạo di chuyển cho các ứng dụng mới bên trong dự án của chúng tôi. Lần đầu tiên chúng tôi muốn tạo di chuyển cho một ứng dụng mới, chúng tôi phải rõ ràng hơn về nó
Để tạo một tập hợp các lần di chuyển cho ứng dụng
from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
0, hãy chạy lệnh saupython manage.py makemigrations authentication
Thao tác này sẽ tạo quá trình di chuyển ban đầu cho ứng dụng
from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
0. Trong tương lai, bất cứ khi nào bạn muốn tạo di chuyển cho ứng dụng from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
0, bạn chỉ cần chạy >>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
3Thực hiện di chuyển mặc định bằng cách chạy
>>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
3Tạo lần di chuyển ban đầu cho ứng dụng
from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
0 bằng cách chạy from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
6Bây giờ chúng ta có thể áp dụng chúng bằng cách chạy lệnh sau
Không giống như lệnh
from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
7, bạn không bao giờ cần chỉ định ứng dụng sẽ được di chuyển khi chạy lệnh from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
8Áp dụng các lần di chuyển mới tạo bằng cách chạy
from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
9Người dùng đầu tiên của chúng tôi
Chúng tôi đã tạo mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 và cơ sở dữ liệu của chúng tôi đang hoạt động. Việc tiếp theo cần làm là tạo đối tượng # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 đầu tiên của chúng ta. Chúng tôi sẽ biến người dùng này thành siêu người dùng vì chúng tôi sẽ sử dụng nó để kiểm tra trang web của mìnhTạo người dùng đầu tiên của bạn bằng cách chạy lệnh sau
python manage.py createsuperuser
Django sẽ hỏi bạn một số câu hỏi như email, tên người dùng và mật khẩu của bạn. Sau khi trả lời, người dùng mới của bạn sẽ được tạo. Xin chúc mừng
Tạo người dùng đầu tiên của bạn bằng cách chạy
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
02Để kiểm tra xem người dùng đã được tạo chưa, hãy bắt đầu bằng cách mở trình bao Django từ dòng lệnh
python manage.py shell_plus
Nếu bạn đã từng sử dụng Django trước đây, bạn có thể quen thuộc với lệnh
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
03, nhưng không quen thuộc với class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
04. class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
04 được cung cấp bởi một thư viện có tên là class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
06, thư viện này đã được đưa vào dự án soạn sẵn mà bạn đã nhân bản trước khi bắt đầu khóa học này. Nó hữu ích vì nó tự động nhập các mô hình cho từng ứng dụng trong cài đặt class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
07. Nó cũng có thể được thiết lập để tự động nhập các tiện ích khácKhi Shell được mở, hãy chạy như sau
GHI CHÚ. Chỉ nhập những gì xuất hiện trên các dòng trước
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
08. Các dòng không đứng trước class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
08 được xuất từ lệnh trước đó>>> user = User.objects.first[]
>>> user.username
‘james'
>>> user.token
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0Njk0MDY2OTksImlkIjoxfQ.qSnwWVD4PJKhKxgLxY0H5mkTE51QnMWv_kqNJVau1go'
Nếu mọi việc suôn sẻ, bạn sẽ thấy đầu ra tương tự như trên
Đăng ký người dùng mới
Hiện tại, người dùng không thể làm bất cứ điều gì thú vị. Nhiệm vụ tiếp theo của chúng tôi là tạo một điểm cuối để đăng ký người dùng mới
Đăng ký nối tiếp
Tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
10Bắt đầu bằng cách tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
10 và nhập mã saufrom rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
Đọc qua mã, đặc biệt chú ý đến các nhận xét và sau đó tiếp tục khi bạn hoàn thành
Trong đoạn mã trên, chúng ta đã tạo một lớp
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
12 kế thừa từ lớp class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
13. class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
13 chỉ là một bản tóm tắt trên đầu trang của class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
15, mà bạn có thể nhớ từ hướng dẫn Django REST Framework [DRF]. class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
16 xử lý một số thứ liên quan đến việc sắp xếp theo thứ tự các mô hình Django cho chúng tôi, vì vậy chúng tôi không cần phảiMột điều khác cần chỉ ra là nó cho phép bạn chỉ định hai phương thức.
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
17 và class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
18. Trong ví dụ trên, chúng tôi đã viết phương thức class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
17 của riêng mình bằng cách sử dụng class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
20, nhưng chúng tôi không chỉ định phương thức class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
18. Trong trường hợp này, DRF sẽ sử dụng phương pháp class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
18 mặc định của chính nó để cập nhật người dùngĐăng kýAPIView
Bây giờ chúng tôi có thể tuần tự hóa các yêu cầu và phản hồi để đăng ký người dùng. Tiếp theo, chúng tôi muốn tạo chế độ xem để sử dụng làm điểm cuối, vì vậy khách hàng sẽ có một URL để nhấn để tạo người dùng mới
Tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23 và gõ như sauclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
0Hãy nói về một vài điều mới trong đoạn trích này
- Thuộc tính
24 là cách chúng tôi quyết định ai có thể sử dụng điểm cuối này. Chúng tôi có thể hạn chế điều này đối với người dùng được xác thực hoặc người dùng quản trị. Chúng tôi cũng có thể cho phép người dùng được xác thực hay không dựa trên việc điểm cuối mà họ đang truy cập có "an toàn" hay không — điều đó có nghĩa là điểm cuối là một yêu cầuclass UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
25,class UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
26 hoặcclass UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
27. Đối với khóa học này, bạn chỉ cần biết khoảngclass UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
25 yêu cầu. Chúng ta sẽ nói thêm vềclass UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
29 sauclass UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
- Tạo bộ nối tiếp, xác thực bộ nối tiếp, lưu mẫu bộ nối tiếp mà bạn thấy bên trong phương thức
30 rất phổ biến khi sử dụng DRF. Bạn sẽ muốn làm quen với mẫu này vì bạn sẽ sử dụng nó rất nhiềuclass UserManager[BaseUserManager]: """ Django requires that custom users define their own Manager class. By inheriting from `BaseUserManager`, we get a lot of the same code used by Django to create a `User`. All we have to do is override the `create_user` function which we will use to create `User` objects. """ def create_user[self, username, email, password=None]: """Create and return a `User` with an email, username and password.""" if username is None: raise TypeError['Users must have a username.'] if email is None: raise TypeError['Users must have an email address.'] 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]: """ Create and return a `User` with superuser [admin] permissions. """ if password is None: raise TypeError['Superusers must have a password.'] user = self.create_user[username, email, password] user.is_superuser = True user.is_staff = True user.save[] return user
Tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23Bây giờ chúng ta cần thiết lập định tuyến cho dự án của mình. Có một số thay đổi được giới thiệu từ Django 1. x => 2. x chuyển từ
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
32 sang class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
33. Có khá nhiều câu hỏi về việc điều chỉnh url biểu thức chính quy cũ sang cách thực hiện mới trong một đường dẫn. Considerate Code đã tạo một URL tới Path Cheatsheet và ghi lại sự thay đổi. Một số trường hợp đặc biệt có thể cần phải sử dụng class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
34 và sử dụng các biểu thức thông thườngTạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
35 và đặt phần sau vào tệp để xử lý các tuyến đường của chúng tôi cho ứng dụng nàyclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
1Nếu bạn đến từ một framework khác như Rails, thông thường bạn sẽ đặt tất cả các route của mình vào một tệp duy nhất. Mặc dù bạn có thể làm điều này trong Django, nhưng cách tốt nhất là tạo các đường dẫn dành riêng cho ứng dụng mô-đun. Điều này buộc bạn phải suy nghĩ về thiết kế ứng dụng của mình và giữ chúng độc lập và có thể tái sử dụng. Đó là những gì chúng tôi đã làm ở đây. Chúng tôi cũng đã chỉ định
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
36 để chúng tôi có thể sử dụng một class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
37 và giữ cho ứng dụng của chúng tôi theo mô-đun. Bây giờ, hãy đưa tệp trên vào tệp URL toàn cầu của chúng tôiTạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
38Mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
39 và bạn sẽ thấy dòng sau ở gần đầu tệpclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
2Điều đầu tiên chúng tôi muốn làm là nhập một phương thức có tên là
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
37 từ class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
41class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
3Phương pháp
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
37 hãy bao gồm một tệp class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
43 khác mà không cần phải thực hiện một loạt công việc như nhập và sau đó đăng ký lại các tuyến đường trong tệp nàyXa hơn nữa bạn sẽ thấy như sau
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
4Hãy cập nhật điều này để bao gồm tệp
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
43 mới của chúng tôiclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
5Bao gồm các URL từ ứng dụng
from rest_framework import serializers
from .models import User
class RegistrationSerializer[serializers.ModelSerializer]:
"""Serializers registration requests and creates a new user."""
# Ensure passwords are at least 8 characters long, no longer than 128
# characters, and can not be read by the client.
password = serializers.CharField[
max_length=128,
min_length=8,
write_only=True
]
# The client should not be able to send a token along with a registration
# request. Making `token` read-only handles that for us.
token = serializers.CharField[max_length=255, read_only=True]
class Meta:
model = User
# List all of the fields that could possibly be included in a request
# or response, including fields specified explicitly above.
fields = ['email', 'username', 'password', 'token']
def create[self, validated_data]:
# Use the `create_user` method we wrote earlier to create a new user.
return User.objects.create_user[**validated_data]
0 trong tệp chính class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
43Đăng ký người dùng với Postman
Bây giờ chúng tôi đã tạo mô hình
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 và thêm một điểm cuối để đăng ký người dùng mới, chúng tôi sẽ chạy kiểm tra nhanh để đảm bảo rằng chúng tôi đang đi đúng hướng. Để làm điều này, chúng tôi sẽ sử dụng một công cụ có tên là Postman với bộ sưu tập các điểm cuối được tạo sẵnNếu bạn chưa từng sử dụng Postman trước đây, hãy xem hướng dẫn Thử nghiệm ứng dụng Conduit sử dụng Postman của chúng tôi
Mở Postman và sử dụng yêu cầu "Đăng ký" bên trong thư mục "Auth" để tạo người dùng mới
Thực hiện yêu cầu Postman đầu tiên của bạn
Đáng kinh ngạc. Hiện tại chúng tôi đang đạt được một số tiến bộ thực sự
Có một điều chúng ta cần phải sửa chữa mặc dù. Lưu ý cách phản hồi từ yêu cầu "Đăng ký" có tất cả thông tin của người dùng ở cấp cơ sở. Khách hàng của chúng tôi mong đợi thông tin này được đặt tên trong "người dùng. " Để làm điều đó, chúng tôi sẽ cần tạo trình kết xuất DRF tùy chỉnh
Kết xuất các đối tượng Người dùng
Tạo một tệp có tên
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
48 và nhập nội dung sauclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
6Tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
48Không có gì mới hoặc thú vị xảy ra ở đây, vì vậy chỉ cần đọc qua các nhận xét trong đoạn trích và sau đó chúng ta có thể tiếp tục
Bây giờ hãy mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23 và nhập class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
51 bằng cách thêm dòng sau vào đầu tệp của bạnclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
7Bạn cũng cần đặt thuộc tính
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
52 của lớp class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
53 như vậyclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
8Cập nhật
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
53 để sử dụng lớp trình kết xuất class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
51Với
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
51 tại chỗ, hãy tiếp tục và sử dụng yêu cầu Postman "Đăng ký" để tạo người dùng mới. Lưu ý lần này phản hồi nằm trong không gian tên "người dùng"Đăng ký người dùng mới với Postman
Đăng nhập người dùng
Vì người dùng hiện có thể đăng ký Conduit, chúng tôi cần xây dựng một cách để họ đăng nhập vào tài khoản của mình. Trong bài học này, chúng ta sẽ thêm serializer và view cần thiết để người dùng đăng nhập. Chúng tôi cũng sẽ bắt đầu xem xét cách API của chúng tôi sẽ xử lý lỗi
Đăng nhậpSerializer
Mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
10 và thêm phần nhập sau vào đầu tệpclass UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
9Sau đó, tạo bộ nối tiếp sau trong cùng một tệp
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
0Thêm lớp
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
58 mới vào class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
10Với serializer tại chỗ, hãy chuyển sang tạo chế độ xem
Đăng nhậpAPIView
Mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23 và cập nhật lần nhập sauclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
1Sau đó thêm chế độ xem đăng nhập mới
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
2Thêm lớp
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
61 mới vào class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23Mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
38 và cập nhật lần nhập sauclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
3Và thêm một quy tắc mới vào danh sách
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
64class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
4Thêm mẫu URL cho
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
61 đến class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
38Đăng nhập người dùng bằng Postman
Tại thời điểm này, người dùng sẽ có thể đăng nhập bằng cách nhấn điểm cuối đăng nhập mới. Hãy kiểm tra điều này. Mở Postman và sử dụng yêu cầu "Đăng nhập" để đăng nhập bằng một trong những người dùng bạn đã tạo trước đó. Nếu nỗ lực đăng nhập thành công, phản hồi sẽ bao gồm mã thông báo có thể được sử dụng trong tương lai khi thực hiện các yêu cầu yêu cầu người dùng được xác thực
Đăng nhập người dùng bằng Postman
Có một cái gì đó khác chúng ta cần phải xử lý ở đây. Thử sử dụng yêu cầu "Đăng nhập" để đăng nhập bằng tổ hợp email/mật khẩu không hợp lệ. Lưu ý phản hồi lỗi. Có hai vấn đề này
Đầu tiên,
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
67 nghe có vẻ lạ. Thông thường, khóa này tương ứng với bất kỳ trường nào khiến bộ nối tiếp không xác thực được. Vì chúng tôi ghi đè phương thức class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
68, thay vì một phương thức dành riêng cho trường, chẳng hạn như _______ 39_______69, Django REST Framework không biết thuộc tính lỗi thuộc trường nào. Giá trị mặc định là class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
67 và vì khách hàng của chúng tôi sẽ sử dụng phím này để hiển thị lỗi, nên chúng tôi sẽ thay đổi giá trị này thành class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
71Thứ hai, khách hàng mong đợi bất kỳ lỗi nào được đặt tên theo khóa
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
72 trong phản hồi JSON, tương tự như cách chúng tôi đặt tên cho các yêu cầu đăng nhập và đăng ký theo khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
73. Chúng tôi sẽ thực hiện điều này bằng cách ghi đè xử lý lỗi mặc định của Django REST Framework [DRF]Ghi đè EXCEPTION_HANDLER và NON_FIELD_ERRORS_KEY
Một trong các cài đặt của DRF được gọi là
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
74 trả về từ điển lỗi. Chúng tôi muốn các lỗi của chúng tôi được đặt tên theo khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
72, vì vậy chúng tôi sẽ phải ghi đè lên class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
74. Chúng tôi cũng sẽ ghi đè class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
77 như đã đề cập trước đóHãy bắt đầu bằng cách tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
78 và thêm đoạn mã sauclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
5Tạo
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
78 với đoạn mã trênSau khi xử lý xong, hãy mở
python manage.py shell_plus
9 và thêm một cài đặt mới vào cuối tệp có tên là class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
81, như vậyclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
6Thêm lệnh
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
81 vào python manage.py shell_plus
9 với các khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
74 và class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
77 như trênĐây là cách chúng tôi ghi đè cài đặt trong DRF. Chúng tôi sẽ thêm một cài đặt nữa khi chúng tôi bắt đầu viết các chế độ xem yêu cầu người dùng phải được xác thực
Hãy thử gửi một yêu cầu đăng nhập khác bằng Postman. Đảm bảo sử dụng kết hợp email/mật khẩu không hợp lệ
Sử dụng Postman để đăng nhập bằng tên người dùng và mật khẩu không hợp lệ. Đảm bảo rằng phản hồi được định dạng như chúng ta đã thảo luận trước đó
Cập nhật UserJSONRenderer
ồ ồ. Vẫn chưa hoàn toàn như những gì chúng ta muốn. Bây giờ chúng tôi đã có khóa
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
72, nhưng mọi thứ được đặt tên theo khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
73. Điều đó không tốtHãy cập nhật
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
51 để kiểm tra khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
72 và thực hiện mọi thứ hơi khác một chút. Mở class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
48 và thực hiện những thay đổi nàyclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
7Cập nhật
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
51 trong class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
48 để xử lý trường hợp trong đó class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
93 chứa khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
72Bây giờ hãy gửi yêu cầu đăng nhập với Postman một lần nữa và tất cả sẽ ổn
Sử dụng Postman để đăng nhập bằng tên người dùng và mật khẩu không hợp lệ. Đảm bảo phản hồi có khóa
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
95 thay vì khóa class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
72Truy xuất và cập nhật người dùng
Người dùng có thể đăng ký tài khoản mới và đăng nhập vào các tài khoản đó. Bây giờ người dùng sẽ cần một cách để truy xuất và cập nhật thông tin của họ. Hãy triển khai điều này trước khi chuyển sang tạo hồ sơ người dùng
Trình nối tiếp người dùng
Chúng tôi sẽ tạo thêm một serializer cho hồ sơ. Chúng tôi đã có bộ tuần tự hóa cho các yêu cầu đăng nhập và đăng ký, nhưng chúng tôi cũng cần có khả năng tuần tự hóa các đối tượng người dùng
Mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
10 và thêm vào như sauclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
8Thêm lớp
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
98 mới vào class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
10Cần chỉ ra rằng chúng tôi không xác định rõ ràng phương thức
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
17 trong bộ tuần tự hóa vì DRF cung cấp phương thức class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
17 mặc định cho tất cả các phiên bản của class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
13. Có thể tạo người dùng với bộ nối tiếp này, nhưng chúng tôi muốn việc tạo # Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 được xử lý bởi class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
12Mở
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23 và cập nhật các mục nhập như vậyclass User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
9Bên dưới phần nhập, tạo chế độ xem mới có tên là
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
06# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
0Thêm lớp
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
06 mới vào class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
23Bây giờ, hãy chuyển đến
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
38 và cập nhật phần nhập để bao gồm class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
06# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
1Và thêm một tuyến đường mới vào
class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
64# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
2Thêm mẫu URL cho
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
06 đến class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
38Mở lại Postman và gửi yêu cầu "Người dùng hiện tại". Bạn sẽ gặp lỗi với phản hồi giống như thế này
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
3Sử dụng Postman để yêu cầu dữ liệu về người dùng hiện tại. Bạn sẽ gặp lỗi khi nói
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
14Django có ý tưởng về phụ trợ xác thực. Không đi sâu vào quá nhiều chi tiết, phụ trợ về cơ bản là một kế hoạch để quyết định xem người dùng có được xác thực hay không. Chúng tôi sẽ cần tạo một chương trình phụ trợ tùy chỉnh để hỗ trợ JWT vì điều này không được Django và Django REST Framework [DRF] hỗ trợ theo mặc định
Tạo và mở
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
15 và thêm đoạn mã sau# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
4Tạo
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
15Có rất nhiều logic và ngoại lệ được đưa vào tệp này, nhưng mã này khá đơn giản. Tất cả những gì chúng tôi đã làm là liệt kê các điều kiện mà người dùng sẽ không được xác thực và đưa ra một ngoại lệ nếu bất kỳ điều kiện nào trong số đó là đúng
Không cần đọc thêm ở đây, nhưng vui lòng xem tài liệu về thư viện PyJWT nếu bạn quan tâm
Chúng tôi phải thông báo rõ ràng cho Django REST Framework mà chúng tôi muốn sử dụng phụ trợ xác thực, tương tự như cách chúng tôi đã yêu cầu Django sử dụng mô hình Người dùng tùy chỉnh của chúng tôi
Mở
python manage.py shell_plus
9 và cập nhật chính tả class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
81 bằng một khóa mới# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
5Đăng ký chương trình phụ trợ xác thực JWT của chúng tôi với Django REST Framework bằng cách thêm
class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
19 vào cài đặt class UserManager[BaseUserManager]:
"""
Django requires that custom users define their own Manager class. By
inheriting from `BaseUserManager`, we get a lot of the same code used by
Django to create a `User`.
All we have to do is override the `create_user` function which we will use
to create `User` objects.
"""
def create_user[self, username, email, password=None]:
"""Create and return a `User` with an email, username and password."""
if username is None:
raise TypeError['Users must have a username.']
if email is None:
raise TypeError['Users must have an email address.']
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]:
"""
Create and return a `User` with superuser [admin] permissions.
"""
if password is None:
raise TypeError['Superusers must have a password.']
user = self.create_user[username, email, password]
user.is_superuser = True
user.is_staff = True
user.save[]
return user
81 trong python manage.py shell_plus
9Truy xuất và cập nhật người dùng bằng Postman
Giờ đây, chương trình phụ trợ xác thực mới của chúng tôi đã sẵn sàng, lỗi xác thực mà chúng tôi thấy trước đây sẽ không còn nữa. Kiểm tra điều này bằng cách mở Postman và gửi một yêu cầu "Người dùng hiện tại" khác. Yêu cầu phải thành công và bạn sẽ thấy thông tin về người dùng của mình trong phản hồi
Sử dụng Postman để yêu cầu người dùng hiện tại. Lần này yêu cầu phải thành công
Hãy nhớ rằng chúng tôi đã tạo điểm cuối cập nhật cùng lúc chúng tôi tạo điểm cuối truy xuất. Hãy thử cái này nữa. Gửi yêu cầu có nhãn "Cập nhật người dùng" trong thư mục "Auth" trong Postman. Nếu bạn đã sử dụng nội dung mặc định, thì email của người dùng của bạn sẽ thay đổi. Vui lòng chơi xung quanh với các yêu cầu này để thực hiện các thay đổi đối với người dùng của bạn
Sử dụng Postman để cập nhật người dùng hiện tại. Chơi xung quanh với yêu cầu này để thực hiện các thay đổi đối với người dùng của bạn
Hướng tới những điều tốt đẹp hơn
Đó là tất cả những gì có cho chương này. Chúng tôi đã tạo một mô hình người dùng và người dùng được tuần tự hóa theo ba cách khác nhau. Có bốn điểm cuối mới sáng bóng cho phép người dùng đăng ký, đăng nhập, truy xuất và cập nhật thông tin của họ. Chúng tôi đang có một khởi đầu mạnh mẽ ở đây
Tiếp theo, chúng tôi sẽ tạo hồ sơ cho người dùng của chúng tôi. Bạn có thể nhận thấy rằng người mẫu
# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'
6 khá trần trụi. Chúng tôi chỉ bao gồm những thứ cần thiết để xác thực. Các thông tin khác như tiểu sử và URL hình đại diện sẽ có trong mô hình class User[AbstractBaseUser, PermissionsMixin]:
# Each `User` needs a human-readable unique identifier that we can use to
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField[db_index=True, max_length=255, unique=True]
# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
# the user anyways, we will also use the email for logging in because it is
# the most common form of login credential at the time of writing.
email = models.EmailField[db_index=True, unique=True]
# When a user no longer wishes to use our platform, they may try to delete
# their account. That's a problem for us because the data we collect is
# valuable to us and we don't want to delete it. We
# will simply offer users a way to deactivate their account instead of
# letting them delete it. That way they won't show up on the site anymore,
# but we can still analyze the data.
is_active = models.BooleanField[default=True]
# The `is_staff` flag is expected by Django to determine who can and cannot
# log into the Django admin site. For most users this flag will always be
# false.
is_staff = models.BooleanField[default=False]
# A timestamp representing when this object was created.
created_at = models.DateTimeField[auto_now_add=True]
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField[auto_now=True]
# More fields required by Django when specifying a custom user model.
# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager[]
def __str__[self]:
"""
Returns a string representation of this `User`.
This string is used when a `User` is printed in the console.
"""
return self.email
@property
def token[self]:
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token[].
The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token[]
def get_full_name[self]:
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username
def get_short_name[self]:
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username
def _generate_jwt_token[self]:
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now[] + timedelta[days=60]
token = jwt.encode[{
'id': self.pk,
'exp': int[dt.strftime['%s']]
}, settings.SECRET_KEY, algorithm='HS256']
return token.decode['utf-8']
23 mà chúng ta sẽ xây dựng trong chương tiếp theo