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
- [Django]-Manifest: Line: 1, column: 1, Syntax error on Chrome browser
- [Django]-Better option to check if a particular instance exists django
- [Django]-Django IntegerField with Choice Options (how to create 0-10 integer options)
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
- [Django]-Change a Django form field to a hidden field
- [Django]-Django-cors-headers not work
- [Django]-Filtering using viewsets in django rest framework
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
- [Django]-In Django, can you add a method to querysets?
- [Django]-Django: How to manage development and production settings?
- [Django]-Django: How to access original (unmodified) instance in post_save signal
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
- [Django]-Different initial data for each form in a Django formset
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
- [Django]-Django, redirect all non-authenticated users to landing page
Source:stackexchange.com