我有一个为应用程序创建的中间件,该中间件针对登录的用户检查一些条件。
如果其中任何一项失败,则会引发错误,让用户知道。
问题是该错误在页面顶部显示两次。
中间件如下:
class RegistrationMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
print("In init of middleware")
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
print("Pre-view middle")
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
print("Post-view middle")
...logic stuff....
if invalid_entries:
for problem_reg in invalid_entries:
messages.error(
request, format_html(
"""
Please either
remove or change this registration.
"""
)
)
print('end of view reutrning response')
return response
该错误在页面上显示两次。
我的控制台显示如下内容:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
In init of middleware
Pre-view middle
this is a test of the get_user method
Post-view middle
end of view reutrning response
[25/Feb/2019 09:48:46] "GET /registrations/ HTTP/1.1" 200 21860
[25/Feb/2019 09:48:46] "GET /static/styles.css HTTP/1.1" 200 7082
[25/Feb/2019 09:48:46] "GET /static/registrations/style.css HTTP/1.1" 200 2282
[25/Feb/2019 09:48:46] "GET /static/registrations/index.js HTTP/1.1" 200 1885
[25/Feb/2019 09:48:46] "GET /static/all.min.js HTTP/1.1" 200 3738182
Pre-view middle
Post-view middle
this is a test of the get_user method
end of view reutrning response
Not Found: /favicon.ico
[25/Feb/2019 09:48:47] "GET /favicon.ico HTTP/1.1" 404 2586
我不确定中间件是否是100%检查此类错误的最佳解决方案,但实际上我需要在应用程序的每个视图上都检查相同的代码,因此看来这是正确的处理方式。
我只是试图使其仅触发一次-在视图渲染之前或之后都可以,但是我只需要显示一个错误即可。
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible mt-4" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
{% endfor %}
答案 0 :(得分:0)
在以下情况下具有逻辑:response = self.get_response(request)
导致了问题和行为不一致-因为在视图之后 处理了警报,从而导致错误加载到下一步刷新,冲洗并重复,并且在大多数情况下重复错误。
将其移至之前,视图处理解决了该问题并有助于使其保持一致。