I've got some middleware I created for an app that checks a few criteria against a logged in user.
If it fails any of those, it kicks off errors letting the user know.
The problem is that the error is showing up twice at the top of the page.
The middleware looks like this:
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
The error shows up twice on the page.
My console shows something like this:
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
I'm not sure middleware is 100% the best solution to check for errors like this, but I need to check that same bit of code on essentially every view in the app so it seems like the right way to handle this.
I'm just trying to make it so it just fires once - either before or after the view renders is fine, but I only need it to show one error.
{% 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 %}