django HttpResponse Location redirect

Viewed 1270

I am trying to redirect to another page when http response is True I have added response['Location'] = 'login.html' but it's not working, I am getting a page with True written but not the login page. Can you help me I am new to django.

I have written this code

if user_obj:
    response = HttpResponse(True)
    response['Location'] = 'login.html'
    return response
else:
    return HttpResponse(False)
3 Answers

from django.urls import reverse

return HttpResponseRedirect(reverse('url_name'))

You can simple use Django core redirect function.

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

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.

Related