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('订单页面')
cbv加装饰器
-先导入:from django.utils.decorators import method_decorator
-1 可以在方法上加装饰器:
@method_decorator(login_auth)
-2 可以在类上加
@method_decorator(login_auth,name='post')
@method_decorator(login_auth,name='get')
-3 可以加在dishpatch方法上
@method_decorator(login_auth)
一旦加在dishpatch,说明,所有方法都加了装饰器