How to check if a name/value pair exists when posting data?
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.
@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']
Most logically:
if not 'number' in request.POST:
Python convention:
if 'number' not in request.POST:
Both work in exactly the same way.
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,
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
精彩评论