我已经为应用程序创建了一些中间件,可以根据登录用户检查一些条件。
如果它失败了,它就会启动让用户知道的错误。
问题是错误在页面顶部出现两次。
中间件看起来像这样:
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 %}
以下逻辑:response = self.get_response(request)
导致问题和不一致的行为 - 因为警报在视图之后被处理,反过来导致错误被加载到下一次刷新并冲洗和重复,并且大部分时间错误被重复。
在视图处理之前将其移动到修复问题并帮助使其保持一致。