How to return HTTP 400 response in Django?

DjangoPython 2.7

Django Problem Overview


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

Django Solutions


Solution 1 - Django

From my previous comment :

You can return a HttpResponseBadRequest

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

Solution 2 - Django

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

Solution 3 - Django

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

Solution 4 - Django

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkmnlView Question on Stackoverflow
Solution 1 - DjangoAmbroiseView Answer on Stackoverflow
Solution 2 - DjangoBrian ChapmanView Answer on Stackoverflow
Solution 3 - DjangorgilliganView Answer on Stackoverflow
Solution 4 - DjangomimoView Answer on Stackoverflow