Sobes.tech
Junior — Middle

How can you send an error status response in Django when receiving incorrect data from the client?

sobes.tech AI

Answer from AI

In Django, to send an error response when receiving incorrect data from a client, you can use the HttpResponse class with the appropriate status or specialized classes from django.http, such as HttpResponseBadRequest (status 400). You can also explicitly specify the status in HttpResponse.

Example:

from django.http import HttpResponseBadRequest

def my_view(request):
    if not valid_data(request):
        return HttpResponseBadRequest("Invalid data")
    # process request

Or using HttpResponse with a specified status:

from django.http import HttpResponse

def my_view(request):
    if not valid_data(request):
        return HttpResponse("Invalid data", status=400)
    # process request