How to redirect url from middleware?
Infinite loop problem.
I intend to redirect the user to a client registration url if the registration has not yet been completed.
def check_user_active(get_response):
def middleware(request):
response = get_response(request)
try:
print(Cliente.objects.get(usuario_id=request.user.id))
except Cliente.DoesNotExist:
return redirect('confirm')
return response
return middleware
Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .
Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level “plugin” system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function.
the actual reverse function is used for performing the reverse happen. This method will be responsible for getting the new url value reversed. With the reverse function the name of the redirect url has to be specified. The name of url value specified here will for the redirect url name from the url's.py file.
HttpResponseRedirect is a subclass of HttpResponse (source code) in the Django web framework that returns the HTTP 302 status code, indicating the URL resource was found but temporarily moved to a different URL. This class is most frequently used as a return object from a Django view.
Every request to server goes through Middleware. Hence, when you are going to confirm
page, the request goes through middleware again. So its better put some condition here so that it ignores confirm
url. You can try like this:
def check_user_active(get_response):
def middleware(request):
response = get_response(request)
if not request.path == "confirm":
try:
print(Cliente.objects.get(usuario_id=request.user.id))
except Cliente.DoesNotExist:
return redirect('confirm')
return response
return middleware
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With