Search code examples
pythondjangorequestpycharmbody-parser

How to detect lack of specific field in payload and handle it via exception in Django?


I have a method like this:

@csrf_exempt
def my_method(request):
    if request.method == 'POST':
        payload = json.loads(request.body)
        try:
            name = payload['name']
            return HttpResponse("YES", content_type='text/json')
        except payload['name'].DoesNotExist:
            return HttpResponse("NO", content_type='text/json')

So i want detect and handle error when frontend device not send name field in body. At the moment i have getting several errors when not send name field in body. Please help me to fix this as well i receive better way.


Solution

  • Try this. It might work.

    name = payload.get('name',None)
    if not name:
        return HttpResponse("NO", content_type='text/json')
    else:
        return HttpResponse("YES", content_type='text/json')