1. 程式人生 > >Django之基於session和CBV模式裝飾器實現使用者認證

Django之基於session和CBV模式裝飾器實現使用者認證

models.py

from django.db import models


# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.Login.as_view()),
    url(r
'^order/', views.Order.as_view()), ]

login.html

<form action="" method="post">
    <p>使用者名稱:<input type="text" name="name"></p>
    <p>密碼:<input type="text" name="pwd"></p>
    <input type="submit" value="登入">
</form>

views

from django.shortcuts import
render, HttpResponse, redirect # Create your views here. from django.views import View from app01 import models def login_auth(func): def inner(request, *args, **kwargs): url = request.get_full_path() session_name = request.session.get('name') print(session_name)
if request.session.get('name'): res = func(request, *args, **kwargs) return res else: return redirect('/login/?next=%s' % url) return inner class Login(View): def get(self, request, *args, **kwargs): return render(request, 'login.html') def post(self, request, *args, **kwargs): name = request.POST.get('name') pwd = request.POST.get('pwd') ret = models.User.objects.filter(name=name, pwd=pwd).first() if ret: request.session['id'] = ret.pk request.session['name'] = ret.name url = request.GET.get('next') if url: return redirect(url) else: return redirect('/order/') else: return HttpResponse('登陸失敗') from django.utils.decorators import method_decorator class Order(View): @method_decorator(login_auth) def get(self, request): return HttpResponse('訂單頁面')