[Django]-Django HttpResponse Location redirect

1👍

from django.urls import reverse

return HttpResponseRedirect(reverse(‘url_name’))

1👍

This will not work because you do not use a response in the 300-399 range, which are used for redirection, for example the HTTP 302 Found [wiki]. You furthermore do not need to do this yourself, you can make use of Django’s HttpResponseRedirect(…) [Django-doc]:

if user_obj:
    return HttpResponseRedirect('login.html')

else:
    return HttpResponse(False)

You can also specify content, but normally if the browser makes the redirect, this will not show up for long:

if user_obj:
    return HttpResponseRedirect('login.html', content='True')

else:
    return HttpResponse(False)

Using .html however is (at least by Django) considered "ugly". It is also better to make use of reverse, or redirect to resolve the URL for a given view.

0👍

You can simple use Django core redirect function.

if user_obj:
    // Do something
    return redirect('some_url')

Leave a comment