Django -MD5密码加密与登录

直接贴代码

login_reg.py

from django.shortcuts import render, redirect
from web.forms.login_reg import RegForm
from web import models
import hashlib


def login(request):
    error_msg = ''
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            # 实例化MD5加密方法
            md5 = hashlib.md5()
            # 进行加密,python2可以给字符串加密,python3只能给字节加密
            md5.update(password.encode())
            password_md5 = md5.hexdigest()
            user_obj = models.SysUser.objects.get(USERNAME=username, PASSWORD=password_md5)
            if user_obj:
                return redirect('/web/user/list/')
        except Exception as e:
            print(e)
            error_msg = '用户名或密码错误'

    return render(request, 'login.html', {"error_msg": error_msg})

models.py

from django.db import models
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class SysUser(models.Model):
    """
    系统用户表
    """
    USER_ID = models.AutoField('用户ID', max_length=100, blank=True, primary_key=True)
    USERNAME = models.CharField('用户名', max_length=255, unique=True, blank=True)
    PASSWORD = models.CharField('密码', max_length=255, blank=True)

 

posted @ 2020-03-05 11:16  HoneyCY  阅读(1959)  评论(0编辑  收藏  举报