80

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 
2
  • 2
    Return a HttpResponseBadRequest : docs.djangoproject.com/en/dev/ref/request-response/… You can create an Exception subclass like Http404 to have your own Http400 exception. Commented May 6, 2014 at 10:32
  • Thanks, you could put it in an answer :) Commented May 6, 2014 at 10:34

4 Answers 4

70

From my previous comment :

You can return a HttpResponseBadRequest

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

Sign up to request clarification or add additional context in comments.

1 Comment

Can you show how to create an Exception subclass? Django BaseHandler looks for the Http404 type specifically and always uses status code 404, I can't see a clean way of wiring your own exception and status code in there
31

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

2 Comments

This mapping is also listed in the documentation.
Neither SuspiciousOperation nor 400 are in the code you linked to. I guess it's changed.
24

Since Django 3.2, you can also raise a BadRequest exception:

from django.core.exceptions import BadRequest raise BadRequest('Invalid request.') 

This may be better in some cases than SuspiciousOperation mentioned in another answer, as it does not log a security event; see the doc on exceptions.

Comments

23

If you're using the Django Rest Framework, you have two ways of raising a 400 response in a view:

from rest_framework.exceptions import ValidationError, ParseError raise ValidationError # or raise ParseError 

2 Comments

You can also use raise ValidationError("some message") to render data with the response.
Also, if you want to reffer to a specific field: raise ValidationError({"some_field": "some error"})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.