0

I have Folder model. Folder has foreignkey to User called folders.

In django rest framework I would like to create new Folder object. How do I specify "create object at self.request.user.folders"? under current (out of the box vanilla ModelViewSet) implementation I get error:

folder.folder.user_id may not be NULL

This indicates that a we are trying to create Folder object is without specifying a user.

Is there a built in way or will I need to override the create method and pass user in to the serializer as a argument?

Note that we don't want to pass user_id in request.DATA due to security issues.

models.py:

class FolderModel(Model):
    user = ForeignKey(User, related_name='folders')
    title = CharField(max_length=100)

views.py:

class FolderView(viewsets.ModelViewSet):
    serializer_class = serializers.FoldereSerializer
    model = FolderModel

    def get_queryset(self):
        return self.request.user.folders.all()
2
  • Please show the relevant models, so we can clearly see all relations. Commented Oct 27, 2013 at 11:59
  • @mariodev I have made the updates Commented Oct 27, 2013 at 16:02

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

fom the docs`:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.