How do I return a 401 Unauthorized in Django?

I know this is an old one, but it’s the top Google result for “django 401”, so I thought I’d point this out…

Assuming you’ve already imported django.http.HttpResponse, you can do it in a single line:

return HttpResponse('Unauthorized', status=401)

The 'Unauthorized' string is optional. Easy.

Leave a Comment