0

If a user tries to access a page, I want him to be redirected to the login page, but with a status code 401 (unauthorized). Like this:

if not 'logged_user' in request.session:
    return redirect('mqr_admin:login', status=401)

But the redirect() function doesn't have the status param as the function render() has. What should I do?

Bárbara Este
  • 103
  • 2
  • 11
  • you can either pass it to the function that is called attached to the endpoint, or (I wouldn't) pass it as a url parameter, as in mqr_admin:login?status=401 – E.Serra Dec 18 '18 at 16:25
  • possible duplicate of https://stackoverflow.com/questions/4356842/how-do-i-return-a-401-unauthorized-in-django – Walucas Dec 18 '18 at 16:27
  • If your real goal is to redirect the user to a login page, why do you care what the response code is? – John Gordon Dec 18 '18 at 16:47
  • @JohnGordon I was just wondering if that was a real thing I could do. – Bárbara Este Dec 18 '18 at 17:54

2 Answers2

2

Use the HttpResponse

from django.http import HttpResponse
def yourView(request):    
    return HttpResponse('401 Unauthorized', status=401)

The solution was found here: How do I return a 401 Unauthorized in Django?

Walucas
  • 2,549
  • 1
  • 21
  • 44
0

This is not a thing you can do.

In HTTP, redirects are codes 3xx, mainly 301 and 302. That is how the browser knows to do a redirect at all.

If you return a 4xx status code, the browser will treat it as an error, not a redirect.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895