Reputation: 1052
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?
Upvotes: 0
Views: 1260
Reputation: 26
I do not recommend adding blank=True
and null=True
since as per your model you want unique=True
. This will result to a conflict whenever the second element with name blank is added. if nom
is required, then remove allow_blank=True
so as to always require name.
Upvotes: 0
Reputation: 36
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.
Upvotes: 1
Reputation: 1299
Try to keep your code in English, you can use Django's i18n to translate stuff, also use blank and null for your name field:
class Application(models.Model):
name = models.CharField(_('name'), max_length=255, blank=True, null=True)
sonarqube_url = models.CharField(_('SonarQube URL'), max_length=255, blank=True, null=True)
def __unicode__(self):
return self.name
class ApplicationSerializer(serializers.ModelSerializer):
class Meta:
model = Application
fields = ('id', 'name', 'sonarqube_url')
Let's save flows for later as you don't even have a model relation for them.
Upvotes: 1