版本:django 4.2 python: 3.8
pip install djangorestframework-simplejwt
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号' # unique 唯一索引,此处不能用IngeterField
avatar = models.ImageField(upload_to='avatar', verbose_name='用户头像'
WeChat= models.CharField(max_length=64, blank=True, null=True, verbose_name='微信号')
class Meta:
db_table='user' # 自己定义名称
verbose_name = '用户信息'
verbose_name_plural = verbose_name
REST_FRAMEWORK = {
# 全局配置,若不需要可不配置,但在下面的views.py中,需要配置authentication_classes和permission_classes
'AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
from datetime import timedelta
SIMPLE_JWT= {
'ACESS_TOKEN_LIFETIME': timedelta(hours=5),
'REFRESH_TOKEN_LIFETIME': timedelta(day=1),
'ROTATE_FEFRESH_TOKENS':False,
'AUTH_HEADER_TYPES': ('Bearer',),
}
# 注册自定义的User表,格式为:应用名。表模型
AUTH_USER_MODEL = 'user.User'
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_obtain_pair'),
]
# views.py
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from .models import Banner
from .serializers import BannerModelSerializer
class BannerAPIView(ListAPIView):
queryset = Banner.objects.filter(is_show=True, is_delete=False).order_by('-orders','-id)[: 3] # 筛选前3个图片兵役orders和id倒叙排列
serializer_class = BannerModelSerializer
authentication_classes = [JWTAuthentication] # 此处必须是列表或元组,若全局有配置,则可省略这一步
permission_classes = [IsAuthenticated] # 此处必须是列表或元组,若全局有配置,则可省略这一步
# serializers.py
from rest_framework import serializer
from .models import Banner
class BannerSerializer(serializers.ModelSerializer):
class Meta:
model = Banner
fields = '__all__'