Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect url from middleware in Django?

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
like image 407
marcelo.delta Avatar asked Feb 05 '19 05:02

marcelo.delta


People also ask

How do I redirect in Django?

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/ .

How does middleware work in Django?

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.

What is reverse redirect in Django?

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.

What is HttpResponseRedirect in Django?

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.


1 Answers

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
like image 103
ruddra Avatar answered Nov 14 '22 22:11

ruddra