[Django]-How to return HTTP 400 response in Django?

68👍

From my previous comment :

You can return a HttpResponseBadRequest

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

30👍

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

21👍

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

17👍

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.

👤mimo

Leave a comment