Cheng
Cheng

Reputation: 17904

DRF how to save a model with a foreign key to the User object

I have the following model:

class Journal(models.Model):
    project_name = models.TextField()
    intro = models.TextField(blank=True)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    creator = models.ForeignKey(User)
    group = models.OneToOneField(Group)
    contact_info = models.TextField(blank=True)
    allow_anon = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

I would like to save a record of this model when users submit a form. The values of all the required fields are submitted along with the form so I assume request.data would have them in it except for the creator field.

Since I use token authentication, a token that can identify the user is passed within the HTTP header. According to this post, I can use request.META('whatever') to pull out this token key from the header. Then I will be able to retrieve the user instance based on the token.

So far so good, my question is the next step, how can I write a serializer that can take request.data and a user instance when saving?

I think I should use a ModelSerializer based on the model defined above. But how can I turn the user instance into a serializable form so that the ModelSerializer can consume while saving?

Upvotes: 3

Views: 1563

Answers (2)

mariodev
mariodev

Reputation: 15519

When you're correctly authenticated by token, then you should have a user attribute available in request object.

So depending where you add the logic for passing user object, you can have it in the generic view:

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

or inside serializer (assuming your view is passing context):

def create(self, validated_data):
    data = validated_data.copy()
    data['user'] = self.context['request'].user

    return super(JournalSerializer, self).create(data)

Upvotes: 6

ofnowhere
ofnowhere

Reputation: 1135

This should work.

data = request.data
data['creator'] = user_id  # fetch user_id from metadata first
serializer = YourSerializer(data=data, partial=True)
if serializer.is_valid():
    serializer.save()

Please comment if you need any further clarification , or face any issues.

Upvotes: 0

Related Questions