django实操:换用自建mysql用户表(一次失败的经历)

前言

别想了,基础不扎实的话,还是老老实实用django自带的用户模块吧!这是一次耗时而且失败了的经历。

因为是一次失败的经历,这里我给出一些残酷的经验。

实操

重写用户模型

这是我唯一成功的案例,你需要建一个类似如下的django-orm模型

mysql_models.py

python 复制代码
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class TpUserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError('The Username field must be set')
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self.create_user(username, password, **extra_fields)

    def authenticate(self, request, username=None, password=None):
        try:
            user = self.model.objects.get(username=username)
            if user.check_password(password) and user.state == 1 and user.user_type == 1:
                return user
        except self.model.DoesNotExist:
            return None


class TpUser(AbstractBaseUser):
    user_id = models.AutoField(primary_key=True, db_comment='自增id')
    user_type = models.IntegerField(blank=True, null=True, db_comment='用户类型,0为服务商,1为客户')
    username = models.CharField(unique=True, max_length=255, blank=True, null=True, db_comment='用户名')
    email = models.CharField(max_length=255, blank=True, null=True, db_comment='邮箱')
    is_active = models.IntegerField(blank=True, null=True, db_comment='是否')
    last_login = models.DateTimeField(blank=True, null=True, db_comment='上次登入时间')
    secret = models.CharField(max_length=255, blank=True, null=True, db_comment='授权码')
    password = models.CharField(max_length=255, blank=True, null=True, db_comment='密码')
    account_id = models.CharField(max_length=255, blank=True, null=True, db_comment='账户编码')
    create_time = models.DateTimeField(blank=True, null=True, db_comment='创建时间')
    state = models.IntegerField(blank=True, null=True, db_comment='当前状态,0为未启用,1为正常使用,2为封禁')

    objects = TpUserManager()  # 可能需要自定义用户管理器

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        managed = False
        db_table = 'tp_user'

同目录__init__.py

python 复制代码
from .mysql_models import TpUser

setting.py

python 复制代码
INSTALLED_APPS = [
    ...
    'youproject',
    ...
]

AUTH_USER_MODEL = 'youproject.TpUser'

遗憾点

authenticate和login均没有生效

按理来讲,我继承了django原生auth的功能,但实际上两个方法都绕过了我改写的数据表,不知道最终调用了哪里的数据,导致登入功能完全无效。

python 复制代码
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login


def user_input_check(username, password):
    message = ''
    if len(username) > 16:
        message = "用户名不得超过16位!"
    elif len(password) < 6:
        message = "密码不得少于6位!"
    elif len(password) > 16:
        message = "密码不得超过16位!"
    if message:
        return False, message
    else:
        return True, ''


def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print(username, password)
        ret, msg = user_input_check(username, password)
        if ret:
            user = authenticate(request, username=username, password=password)
            if user:
                login(request, user)
                return redirect('/welcome')  # 替换 'welcome' 为你应用的主页视图名
            else:
                messages.error(request, "用户名或密码错误!")
        else:
            messages.error(request, msg)

    return render(request, 'user/login.html')

为此,我十分头疼,并花费了若干小时去解决,但最终决定放弃,转而采用触发器或者主动脚本的方式来实现自写数据表和django默认auth表的交互,进而实现django用户管理。

相关推荐
AIAdvocate6 分钟前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼7 分钟前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
这孩子叫逆1 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql
FreakStudio2 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
redcocal3 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
artificiali4 小时前
Anaconda配置pytorch的基本操作
人工智能·pytorch·python
掘根4 小时前
【网络】高级IO——poll版本TCP服务器
网络·数据库·sql·网络协议·tcp/ip·mysql·网络安全
RaidenQ4 小时前
2024.9.13 Python与图像处理新国大EE5731课程大作业,索贝尔算子计算边缘,高斯核模糊边缘,Haar小波计算边缘
图像处理·python·算法·课程设计
花生了什么树~.4 小时前
python基础知识(六)--字典遍历、公共运算符、公共方法、函数、变量分类、参数分类、拆包、引用
开发语言·python
Trouvaille ~5 小时前
【Python篇】深度探索NumPy(下篇):从科学计算到机器学习的高效实战技巧
图像处理·python·机器学习·numpy·信号处理·时间序列分析·科学计算