[Solved]-DJango REST Framework Read Only field


You could create a different model serializer for each use case (update, create):

specifying that field in read_only_fields in your model serializer:

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('a', 'nother', 'field')
        read_only_fields = ('owner',)

for django forms instead you set the disabled field:

class MyModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super().__init__(*args, **kwargs)
       form.fields['owner'].widget.attrs['disabled'] = True


You can do this by overriding the “update” method as follows:

  def update(self, instance, validated_data):                                                     
      if 'owner' in validated_data:                                                              
          del validated_data['owner']                                                            
      return super().update(instance, validated_data)

This will silently ignore the owner field on updates. If you want to you may instead “raise ValidationError(‘owner may not be set on updates’)” but if you do so you may want to read the model instance and only raise the error if it’s actually a change to avoid false positives.

Also, if you’re using the python2, the “super” call needs to be “super(GarageSerializer, self)” or some such.

Leave a comment