How to check if a name/value pair exists when posting data?

Viewed 41126

I'm not able to find the proper syntax for doing what I want to do. I want to do something if a name/value pair is not present. Here is the code in my view:

if (!request.POST['number']):
    # do something

What is the proper way to accomplish something like the above? I am getting a syntax error when I try this.

4 Answers

You can use a custom decorator to achieve this and throw an error if the field's requested fields are not sent from the front-end.

from typing import List
from rest_framework import status
from rest_framework.response import Response


def required_fields(dataKey: str, fields: List):
    def decorator_func(og_func, *args, **kwargs):
        def wrapper_func(request, *args, **kwargs):
            data = None
            if dataKey == 'data':
                data = request.data
            elif dataKey == 'GET':
                data = request.GET
            for field in fields:
                if field not in data:
                    return Response('invalid fields', status=status.HTTP_400_BAD_REQUEST)
            return og_func(request, *args, **kwargs)
        return wrapper_func
    return decorator_func

And now you can do:

@api_view(['POST'])
@required_field('data',['field1', 'field2']) # use 'GET' instead of 'data' to check for a GET request.
def some_view(request):
data = request.data
... do something 
Related