赞
踩
基本步骤:
1、自定义的用户表继承AbstractUser;
2、settings.py添加配置,指向用户表:AUTH_USER_MODEL = ‘myUser.Account’(子项目名称.用户表models名称);
3、python manage.py makemigrations
4、python manage.py migrate
# 签发:
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
# 生成token:
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
# 通过headers获取token:
token = request.META.get('HTTP_AUTHORIZATION')
# 情况一:token的传参格式为JWT xxxx
token = request.META.get('HTTP_AUTHORIZATION')[4:]
# 情况二:token的传参格式为TOKEN xxxx
token = request.META.get('HTTP_AUTHORIZATION')[7:]
# 然后解析出user_id和username:
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
话不多说,直接上代码
from django.db import models from django.contrib.auth.models import AbstractUser """ 基类:可以把通用的字段定义这里,其他地方继承基类即可拥有 """ class BaseModel(models.Model): updated_tm = models.DateTimeField(auto_now=True) created_tm = models.DateTimeField(auto_now_add=True) class Meta: abstract = True """ 用户表:自定义的用户表 想要使用自定义的用户表进行登录验证,需要满足下面的条件: 1、需要继承AbstractUser; 2、settings.py添加配置:AUTH_USER_MODEL = 'myUser.Account'(子项目名称.用户表models名称) """ class Account(AbstractUser, BaseModel): user_id = models.AutoField(help_text="用户id", primary_key=True) username = models.SlugField(max_length=128, help_text="用户名", unique=True) password = models.CharField(max_length=128, help_text="用户密码") nickname = models.CharField(max_length=128, help_text="用户昵称") # 指定数据库表信息 class Meta: db_table = 'user' verbose_name = '用户基础信息' verbose_name_plural = verbose_name """ 项目表:重点关注editor字段 """ class ProjectList(BaseModel): """项目基本信息""" project_id = models.AutoField(help_text="项目id", primary_key=True) project_name = models.SlugField(max_length=128, help_text="项目名", unique=True) editor = models.CharField(max_length=128, default='admin', help_text="编辑者") class Meta: db_table = 'project' verbose_name = '项目基本信息' verbose_name_plural = verbose_name
from rest_framework import serializers
from myUser.models import BaseModel, Account
from myProject.models import ProjectList
import time
class BaseSerializer(serializers.ModelSerializer):
"""基类序列化器"""
create_tm_format = serializers.DateTimeField(source="created_tm",
format="%Y-%m-%d %H:%M:%
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。