我正在为Django应用程序编写一些中间件,并且在尝试编写process_template_response函数时陷入困境。我熟悉模板和渲染,但是对于如何基于我在process_request函数中编写的一些if / else语句将字典值传递到模板感到困惑。我的中间件的目的是根据身份验证状态发出重定向,并且当有人请求不应该看到的页面时,我需要传递一条消息“未授权”。
这是中间件:
import re
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponsePermanentRedirect
class CustomMiddleware(MiddlewareMixin):
def __init__(self, get_response = None):
self.get_response = get_response
self.permittedPages = settings.PERMITTED_PAGES
self.noLoginRequired = setting.NO_LOGIN_PAGES
def process_request(self, request):
request_path = request.path.lstrip('/')
if request_path not in noLoginRequired and request_path in permittedPages and request.user.is_authenticated == False: HttpResponseRedirect(settings.LOGIN_URL)
elif request_path not in permittedPages and request.user.is_authenticated: #if the page isn't accessible but the user is logged in
not_found_message = 'This page isn\'t available, redirecting to the home page....'
return HttpResponseRedirect('/home/'), not_found_message
else: #if the page isn't accessible and the user isn't logged in
return HttpResponseRedirect(settings.LOGIN_URL)
def process_template_response(self, request):