[Answer]-Django rest framework create for self.request.user.<model>

0👍

fom the docs`:

def pre_save(self, obj):
    obj.owner = self.request.user

1👍

The original answer no longer works as of DRF 3.0, as the functions have changed. The relevant doc is here.

From the docs:

The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer).

These methods should save the object instance by calling serializer.save(), adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.

For example:

def perform_create(self, serializer):
    # Include the owner attribute directly, rather than from request data.
    instance = serializer.save(owner=self.request.user)
    # Perform a custom post-save action.
    send_email(instance.to_email, instance.message)

Leave a comment