0

I have a simple model:

class Store(models.Model):
    name = models.CharField("address", max_length = 128, null = True, blank = True)
    open = models.PositiveIntegerField("status", default = 1, choices = [(0,0), (1,1)])
    user = models.OneToOneField(User, on_delete = models.CASCADE, )
    

with a simple serializer:

class StoreSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = ["open", "user"]

the view:

class StateViewSet(viewsets.ModelViewSet):
    serializer_class = StoreSerializer
    http_method_names = ['get', 'put', 'head']
    authentication_classes = [SessionAuthentication,]
    permission_classes = [IsAuthenticated,]

    def list(self, request):
        usr = request.user
        stores = Store.objects.filter(user = usr)
        return Response(stores.values_list("name", flat = True))

    def put(self, request):
        usr = request.user
        Store.objects.filter(user = usr).update(state = request.data["state"])
        return Response("updated")

enter image description here

What I want is, to get rid of the user field - only the current user may change the state anyway, so it is already a preset value. I know I omit name, bc its null = True, blank = True, but how can I preset user to request.user and let the dropdown disappear?

xtlc
  • 1,070
  • 1
  • 15
  • 41

1 Answers1

1

You can set the read_only_fields in Meta options of the serializer class

class StoreSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = ["open", "user"]
        read_only_fields = ("user",)

Note that, this will only exclude/hide the user from the HTML form, and won't do a preset.

JPG
  • 82,442
  • 19
  • 127
  • 206
  • can I do the preset somewhere too? Someone could just inject another user with the use of CURL/Postman or HTML manipulation in devtools? Or just by validation methods? – xtlc Apr 08 '21 at 15:36
  • 1
    No, DRF will not accept any input for the `user` field since we've set the `user` in the `read_only_fields` – JPG Apr 08 '21 at 16:09