我正在使用django构建应用程序(注意我对django非常新)。我想从现有视图中添加重定向。
视图中的对象:
from core.views import generic
class ListViewPublic(generic.ListView):
pass
class BookListView(ListViewPublic):
model = Book
def get_queryset(self):
filter_kwargs = {
'status': Book.STATUS.public,
}
return Book.objects.filter(**filter_kwargs)
def get_context_data(self, **kwargs):
context = super(BookListView, self).get_context_data(**kwargs)
form = SearchForm(load_all=True)
context.update({'form': form})
return context
e.g。
/author
url 我该如何实现这种行为?
答案 0 :(得分:1)
您可以使用login_required装饰器。对于您的自定义需求,它应该重定向到/ author您必须创建自定义装饰器。这样的事情。
from django.utils.decorators import method_decorator
from django.template import RequestContext, Context
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, redirect, render
def custom_login_required(f):
def wrap(request, *args, **kwargs):
"""
this will check user is logged in , if not it will redirect to login page
"""
if request.user.is_authenticated() and request.user.user_profile.role=='author':
return HttpResponseRedirect('/author')
else:
return render_to_response('index.html', locals(), context_instance=RequestContext(request))
return f(request, *args, **kwargs)
wrap.__doc__ = f.__doc__
wrap.__name__ = f.__name__
return wrap
并在上面写上get_context_data。
@method_decorator(custom_login_required)
def get_context_data(self, **kwargs):
context = super(BookListView, self).get_context_data(**kwargs)
form = SearchForm(load_all=True)
context.update({'form': form})
return context