-1

In one of my models i have a created_by field. I want this to be automatically set to the user that created the instance. I saw this: Auto-populating created_by field with Django admin site

However, that only works with the admin site and doesn't work with django rest framework. Any ideas on what I could do? Thanks

  • You can write some middlware to automatically set this: https://stackoverflow.com/q/862522/67579 – Willem Van Onsem Dec 18 '20 at 19:04
  • @WillemVanOnsem Thanks! Would you recommend https://pypi.org/project/django-crum/ or writing it myself? –  Dec 18 '20 at 19:05

1 Answers1

0

You have multiple methods for doing this.

The easiest method is the one suggested by the documentation (https://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save) :

Passing additional attributes to .save()

Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.

You can do so by including additional keyword arguments when calling .save(). For example:

serializer.save(owner=request.user)

Or you can overwrite the .create() method of your serializer, and use self.context:

class FooSerializer(serializers.Serializer):
    bar = serializers.CharField()
    created_by = serializers.IntegerField(read_only=True)  # FK

    def create(self, validated_data):
        created_by = get_object_or_404(User, user=self.context["request"].user)
        foo = Foo()
        foo.bar = validated_data["bar"]
        foo.created_by = created_by
        foo.save()
        return foo
Blusky
  • 3,470
  • 1
  • 19
  • 35