Here dummy code to show my problem:
In my django models.py I have something like:
class MyModel(Model):
test_field = SlugField(blank=True, null=False)
# some other not-null not-blank fields here
def save(self, *args, **kwargs):
self.test_field = .... # Setting with a value calculated form the other not-null not-blank fields
Here my serializer:
from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = [ ...., 'test_field', ]
In my views.py something like:
def post_endpoint(request):
data = JSONParser().parse(request)
serializer = MyModelSerializer(data=data)
if serializer.is_valid():
....
serializer.save()
return JsonResponse(serializer.data, status=201)
This is working as expected: I can send an object to my post_endpoint without my test_field and I get my result with test_field set as expected. serializer.is_valid() returns True in that case.
The problem? I need that same functionality but with a FloatField instead of SlugField. But I noticed serializer.is_valid() returns False in that case and I get a "This field may not be null." in serializer.errors in my view function.
How is FloatField different from SlugField ? How can I get the expected functionality also with FloatField?
djangorestframework==3.14.0 Django==4.0.5
I have give it a try but it's working perfectly fine:
model
serializer
view
urls
request
One thing I've noticed strage in your code is the JSON parsing of request for serializer input data. This is not required as log as you follow the procedure like above.