I am building my first API with the Django-Rest-Framework and I am a bit stuck in the validation process. Hope this is a simple answer, but I could not understand it from a 6-part tutorial ...
I have a model:
class XYZMeta(models.Model):
id = models.AutoField(primary_key=True)
xyz_id = models.ForeignKey(XYZ)
user_id = models.ForeignKey(User)
field_name = models.CharField(blank=True, max_length=50)
value = models.TextField(blank=True)
And serializer:
class XYZMetaSerializer(serializers.ModelSerializer):
class Meta:
model = XYZMeta
fields = ('id', 'xyz_id', 'user_id', 'field_name', 'value')
And the view:
class XYZMetaViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows xyz metadata to be viewed or edited.
"""
queryset = XYZMeta.objects.all()
serializer_class = serializers.XYZMetaSerializer
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
When I send POST to create a new object, it works fine and uses the identifier of the authorized user, and not any value that I provide. Example:
> curl -X POST -H "Content-Type:application/json" -d '{"xyz_id":"12345",**"user_id":2**,"field_name":"abc","value":"abc comment"}' -u admin:admin http://mysite/xyzmeta/
{"id":2,"dealer_id":12345,**"user_id":1**,"field_name":"abc","value":"abc comment","create_date":"2015-02-22T23:32:27.928991Z"}
However, if I completely leave user_id (since it does not matter), I get the error message that is required for this field:
> curl -X POST -H "Content-Type:application/json" -d '{"xyz_id":"12345","field_name":"abc","value":"abc comment"}' -u admin:admin http://mysite/xyzmeta/
{"user_id":["This field is required."]}
How do I indicate that I want the user_id foreign key fields to be set programmatically during the creation process, and not need to provide a dummy value?