Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DJango REST Framework Read Only field

I have a field owner that is a ForeignKey to User model.

This field is required at the time of creation. But it can not be changed later on.

How to make fields Non-Editable? Is there any other way than creating multiple serializers?

Garage Model

class GarageDetails(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, )
    name = models.CharField(_('Garage Name'), max_length=254, blank=False, null=False, unique=True)
    price = models.IntegerField(_('Price'), blank=False)
    available_from = models.TimeField(_('Available From'), default=datetime.time(6, 00), blank=False)
    available_till = models.TimeField(_('Available till'), default=datetime.time(18, 00), blank=False)
    description = models.TextField(_('Garage Description'), blank=True, null=True)

    create_date = cmodels.UnixTimestampField(_('Date Added'), auto_now_add=True)
    update_date = cmodels.UnixTimestampField(_('Date Added'), auto_created=True)
    is_available = models.BooleanField(_('Available'), default=True)

Serializer

class UserFKSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('id', 'name', 'email', 'mobile')


class GarageSerializer(serializers.ModelSerializer):
    owner = UserFKSerializer(many=False, read_only=True)

    class Meta:
        model = GarageDetails
        fields = '__all__'
        read_only_fields = ('id', 'owner', 'create_date', 'update_date')

Views

class GarageRegister(generics.ListCreateAPIView):
    renderer_classes = (JSONRenderer, )
    permission_classes = (IsAuthenticated, )

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        serialize = GarageSerializer(data=request.data)
        if serialize.is_valid():
            # Create Garage with owner & name

class GarageUpdate(generics.ListCreateAPIView):
    renderer_classes = (JSONRenderer, )
    permission_classes = (IsAuthenticated, )

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        serialize = GarageSerializer(data=request.data)
        if serialize.is_valid():
            # Update Garage but can't update create_date, id, owner & name
like image 892
Himanshu Shankar Avatar asked Apr 04 '17 10:04

Himanshu Shankar


People also ask

What is write only in Django?

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows. write_only. Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

What is Serializers SerializerMethodField ()?

SerializerMethodField. This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature: SerializerMethodField(method_name=None)

How do you get a foreign key field name instead of ID in Django REST Framework?

If you want to show any field of foreign key instead of id then you can use StringRelatedField.


1 Answers

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
like image 94
DRC Avatar answered Oct 14 '22 00:10

DRC