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")
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?
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.