Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return HTTP 400 response in Django?

I want to return a HTTP 400 response from my django view function if the request GET data is invalid and cannot be parsed.

How do I do this? There does not seem to be a corresponding Exception class like there is for 404:

raise Http404 
like image 470
markmnl Avatar asked May 06 '14 10:05

markmnl


People also ask

What is HttpResponse in Django?

HttpResponse Methods – Django It is used to instantiate an HttpResponse object with the given page content and content type. HttpResponse.__setitem__(header, value) It is used to set the given header name to the given value.

What type of object should be returned in Django view?

A view in Django must return a HttpResponse , even if it's empty.

How does Django define views?

In the Django framework, views are Python functions or classes that receive a web request and return a web response. The response can be a simple HTTP response, an HTML template response, or an HTTP redirect response that redirects a user to another page.


2 Answers

From my previous comment :

You can return a HttpResponseBadRequest

Also, you can create an Exception subclass like Http404 to have your own Http400 exception.

like image 164
Ambroise Avatar answered Sep 28 '22 20:09

Ambroise


You can do the following:

from django.core.exceptions import SuspiciousOperation raise SuspiciousOperation("Invalid request; see documentation for correct paramaters") 

SuspiciousOperation is mapped to a 400 response around line 207 of https://github.com/django/django/blob/master/django/core/handlers/base.py

like image 28
Brian Chapman Avatar answered Sep 28 '22 20:09

Brian Chapman