import os from django.shortcuts import render from django.contrib.admin.views.decorators import staff_member_required from django.views.generic import View from django.views.decorators.http import require_POST, require_GET from django.contrib.auth.decorators import login_required # 登录装饰器 from django.utils.decorators import method_decorator from ..news.models import NewsCategory, News from ..news.forms import NewsForm from utils import restful # Create your views here. # staff_member_required(login_url) 用来验证is_staff(User表中的字段)是否为真,判断用户能否登入cms页面, # login_url是不通过验证跳转, 前端通过login函数登录后的user.is_staff判断是否显示 @staff_member_required(login_url='/') def index(request): return render(request, 'cms/index.html') # method_decorator 使装饰器装饰在类上面(装饰器的类装饰器?) login_required 登陆验证,失败跳转 # despatch 类里面有多个方法(get,post).将这些方法都装饰在despatch中,(通过despatch方法确定出get or post 再由login_required装饰)。 @method_decorator(login_required(login_url='/account/login/'), name='dispatch') class WriteNewsView(View): def get(self, request): categories = NewsCategory.objects.all() return render(request, 'cms/write_news1.html', locals()) def post(self, request): forms = NewsForm(request.POST) if forms.is_valid(): cleaned_data = forms.cleaned_data title = cleaned_data.get('title') desc = cleaned_data.get('desc') thumbnail = cleaned_data.get('thumbnail') content = cleaned_data.get('content') author = request.user category_id = cleaned_data.get('category') category = NewsCategory.objects.get(id=category_id) try: News.objects.create( title=title, desc=desc, thumbnail=thumbnail, content=content, category=category, author=author ) return restful.ok() except: return restful.params_error("服务器gg") error = forms.get_first_message() return restful.params_error(error)
# 简化版dispatch. 是View中的方法 def dispatch(self, request, *args, **kwargs): if request.method == "GET": return self.get(request) elif request.method == "POST": return self.post(request)
自定义django登录装饰器
def xfz_auth_required(func): def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return func(request, *args, **kwargs) else: if request.is_ajax(): return restful.params_error(message="请登陆") return redirect('/account/login') return wrapper