欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django简单的注册、登录以及注销(退出)操作

程序员文章站 2022-03-25 11:15:53
...

注册


from django.http import HttpResponseRedirect
from django.shortcuts import render
from account.models import Users

def register(request):
    if request.method == 'GET':
        return render(request, 'account/register.html')

    if request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        password = make_password(password)
        Users.objects.create(
            u_name=name,
            u_password=password
        )
        return HttpResponseRedirect('/account/login/')

登录

import random
import time
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from account.models import Users

def login(request):
    if request.method == 'GET':
        return render(request, 'account/login.html')

    if request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        if Users.objects.filter(u_name=name).exists():
            user = Users.objects.get(u_name=name)
            if check_password(password, user.u_password):
                now_time = time.strftime('%Y%m%d%H%M%S', time.localtime())
                str = 'qwertyuiopasdfghjklmnbvcxz0123456789'
                ticket = ''
                for _ in range(30):
                    ticket += random.choice(str)
                ticket = 'TKT_' + now_time + '_' + ticket
                response = HttpResponseRedirect('/blog/home/')
                user.u_ticket = ticket
                response.set_cookie('ticket', ticket)
                user.save()
                return response
            else:
                return HttpResponse('密码不正确!')
        else:
            return HttpResponse('用户不存在!')

注销/退出

from django.http import HttpResponseRedirect

def logout(request):
if request.method == 'GET':
    response = HttpResponseRedirect('/account/login/')
    response.delete_cookie('ticket')
    return response
相关标签: django