1. 程式人生 > >django簡單的註冊、登入以及登出(退出)操作

django簡單的註冊、登入以及登出(退出)操作

註冊


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