Search code examples
pythondjangopostdjango-rest-framework

Django-Rest-Framework, POST operation: fields is not empty but DRF says is required


Well, i have this model:

class Application(models.Model):
    name = models.CharField("nom", unique=True, max_length=255)
    sonarQube_URL = models.CharField("Url SonarQube", max_length=255,
                                 blank=True, null=True)

    def __unicode__(self):
        return self.name

and this serializer:

class ApplicationSerializer(serializers.ModelSerializer):
    nom = serializers.CharField(source='name', required=True, allow_blank=True)
    url_sonarqube = serializers.CharField(source='sonarQube_URL', required=False)
    flows = FlowSerializer(many=True, read_only=True)

    class Meta:
        model = Application
        fields = ('id', 'nom', 'url_sonarqube', 'flows')

My view is simple:

class ApplicationViewSet(viewsets.ModelViewSet):
    queryset = Application.objects.all()
    serializer_class = ApplicationSerializer

I use this model of permissions in my settings.py:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.DjangoModelPermissions',),
    'PAGE_SIZE': 10,
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    'TEST_REQUEST_RENDERER_CLASSES': (
    'rest_framework.renderers.MultiPartRenderer',
    'rest_framework.renderers.JSONRenderer',
    'rest_framework.renderers.TemplateHTMLRenderer'
    )
}

When I use POST operation on DRF interface (in HTML Form), I filled all the fields of the application Item. As you can see, "required" parameter of "nom" is set to True. And, this is the problem: even if 'nom' is not empty, DRF says "this field is required!". So, I can't POST a new application item. I don't understand why it not works... Where is the mistake?


Solution

  • The error you got is related to the Django Model(Application). It was failing in model level not in serializer level. Add null=True and blank=True to name field in Application model.