Reputation: 1759
@parser_classes([MultiPartParser, FormParser])
@api_view(['POST', ])
def product_list(request):
print(request.POST.get('key'))
print(request.data.get('key'))
print(request.FILES)
When I am sending form data with value of key=null it displays null as string but didn't convert to None what should I do. The work around that I have to do is something like
if request.data.get('key', None) in ['null', None]:
#then do something
But this doesn't seem to be a clean way of doing this. So what should I do?
I expected that django or django rest framework will automatically convert null to None.
Upvotes: 1
Views: 1669
Reputation: 1759
I made a small workaround to solve this issue by designing a middleware. I dont know if its good but it worked for me. I made it first mutable, changed it then made immutable again.
from django import http
from django.utils.deprecation import MiddlewareMixin
class NullStringToNoneMiddleware(MiddlewareMixin):
"""Responsible for converting all string null values to None"""
def process_request(self, request):
request.POST._mutable = True
for j in request.POST:
if request.POST[j] == 'null':
request.POST[j] = None
request.POST._mutable = False
Upvotes: 0
Reputation: 42492
There is no such thing as null/none in HTTP form-data content (in fact there's no such thing as types in the way we'd usually understand, though there can be a content-type associated with each item).
So what happens here is on the javascript side the null
gets converted to a string, added to the data, sent to the server, which just gets a null
string without any more information.
Generally, "null" items would be missing entirely, alternatively, they would have an empty value associated with them.
Either way, this is not an issue with django.
Upvotes: 3