30

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.

Sam R.
  • 16,027
  • 12
  • 69
  • 122
djangon00b
  • 343
  • 1
  • 4
  • 7
  • 1
    Assuming you're new to Python, not only to Django. First, `request.POST` in Django is like a normal Python *dictionary*. So you need to find out *what is the proper syntax to test the presence of a key in a dictionary*. Once you know that, you can google the right thing and find quite a few very similar questions that have been asked on StackOverflow already (for example, http://stackoverflow.com/questions/1602934/what-is-a-good-way-to-test-if-a-key-exists-in-python-dictionary). – Anton Strogonoff Jun 15 '11 at 18:43

4 Answers4

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']
Pablo Castellazzi
  • 4,164
  • 23
  • 20
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
  • 39,200
  • 7
  • 84
  • 86
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
  • 724
  • 7
  • 11
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