Skip to content

Commit d9ee51b

Browse files
committed
Hide user field in api front-end and set default
Before, it was possible in the api font-end for a logged-in user to set the user value of a quote during create or update. This means, the user could set another user as the owner of the quote. This behavior seems unintended. To prevent this option, the user field is defined as a hidden field in the serializer. Hidden fields will not show up in the api frontend form. A quote should have a user assigned to it (even if it is not required on the model level) to allow management (update/delete) of the quote. The quote can only be managed by it's owner. To prevent quotes without an owner, the hidden user field is assigned the default value of the currently logged-in user in the serializer.
1 parent 70ee2b6 commit d9ee51b

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

days/069-072-django-rest/demo/api/serializers.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@
55

66
class QuoteSerializer(serializers.ModelSerializer):
77

8+
# This is not included in the videos. Without this setting, it was possible
9+
# to set the user value to something other than the currently logged-in
10+
# user. This setting hides the user field from the form in the API frontend
11+
# and sets the currently logged-in users as the field value by default.
12+
# See also: https://stackoverflow.com/a/53193276
13+
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
14+
815
class Meta:
916
model = Quote
1017
fields = ('quote', 'author', 'source', 'cover', 'user')

0 commit comments

Comments
 (0)