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
- [Django]-Django admin make a field read-only when modifying obj but required when adding new obj
- [Django]-How do I render jinja2 output to a file in Python instead of a Browser
- [Django]-How to override css in Django Admin?
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
- [Django]-How to set a value of a variable inside a template code?
- [Django]-Auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
- [Django]-Django test app error – Got an error creating the test database: permission denied to create database
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
- [Django]-Django Rest Framework: turn on pagination on a ViewSet (like ModelViewSet pagination)
- [Django]-Create if doesn't exist
- [Django]-How to chcek if a variable is "False" in Django templates?
Source:stackexchange.com