Jenia Be Nice Please
Jenia Be Nice Please

Reputation: 2703

How to handle associating a User with a Model?

I'm building an app that uses Django (well the Django Rest Framework) and I'd like to use Token Based Authentication. I'm not 100% clear on how I'd associate a User with a my Model at runtime.

So, I'll receive a POST request in my View:

if request.method == 'POST':
    ....
    serializer.save()

And then, the flow will go to the post save receiver:

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
    Token.objects.create(user=instance)

I suppose that in my Model, I'll need a reference to the User. But how do I get a new or existing User in the View? I suppose this will be my Model:

class UserPostData:
    some_info = models.DateField()
    user = models.OneToOneField(User)

But how do I handle associating the User with the Model I just saved in the view?

if request.method == 'POST':
    # get_or_create_user()? But there's no username. It's token based auth
    serializer.save()

Upvotes: 0

Views: 69

Answers (1)

prokher
prokher

Reputation: 490

If a request is authenticated then you can extract user object from the request. For example, you can overwrite a method create of your serializer and take request from the context, like the following:

class UserPostDataSerializer(ModelSerializer):
    ...
    def create(self, validated_data):
        user = self.context['request'].user
        new_model = UserPostData.objects.create(user=user,
                                                **validated_data)
        new_model.save()
        return new_model
    ...

Upvotes: 1

Related Questions