[Django]-How to check if a name/value pair exists when posting data?

57๐Ÿ‘

@Thomas gave you the generic way, but there is a shortcut for the particular case of getting a default value when a key does not exist.

number = request.POST.get('number', 0)

This is equivalent to:

if 'number' not in request.POST:
    number = 0
else:
    number = request.POST['number']

31๐Ÿ‘

Most logically:

if not 'number' in request.POST:

Python convention:

if 'number' not in request.POST:

Both work in exactly the same way.

๐Ÿ‘คThomas K

3๐Ÿ‘

What I have used many times is the following in my view:

def some_view(request):

    foobar = False

    if request.GET.get('foobar'):
        foobar = True

    return render(request, 'some_template.html',{
        'foobar': foobar,
    })

Then, in my template I can use the following URL syntax to set foobar:

<a href="{% url 'view_name_in_urls' %}?foobar=True">Link Name</a>

Also, since we returned the foobar variable from the view above, we can use that in the template with other logic blocks (great for navigation!):

<li class="nav-item">
    {% if foobar %}
        <a class="nav-link active" ....
    {% else %}
        <a class="nav-link" ....
    {% endif %}
</li>

Hope it helps,

๐Ÿ‘คDouglas

0๐Ÿ‘

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 

0๐Ÿ‘

number = request.POST.get('number', false)

For me this is much cleaner and readable. but it is same with

number = request.POST.get('number', 0)
๐Ÿ‘คpoliam

Leave a comment