Django rest framework auto-populate filed with user.id
Asked Answered
O

1

6

I cant find a way to auto-populate the field owner of my model.I am using the DRF .If i use ForeignKey the user can choose the owner from a drop down box , but there is no point in that.PLZ HELP i cant make it work.The views.py is not include cause i think there is nothing to do with it.

models.py

class Note(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    cr_date = models.DateTimeField(auto_now_add=True)
    owner = models.CharField(max_length=100)
  # also tried:
  # owner = models.ForeignKey(User, related_name='entries')

class Meta:
    ordering = ('-cr_date',)

def __unicode__(self):
    return self.title

serializers.py

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', "username", 'first_name', 'last_name', )

class NoteSerializer(serializers.ModelSerializer):
    owner = request.user.id <--- wrong , but is what a need.
    # also tried :
    # owner = UserSerializer(required=True)

    class Meta:
        model = Note
        fields = ('title', 'body' )
Obsessive answered 26/3, 2014 at 17:28 Comment(0)
A
12

Django Rest Framework provides a pre_save() method (in generic views & mixins) which you can override.

class NoteSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username') # Make sure owner is associated with the User model in your models.py

Then something like this in your view class:

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

REFERENCES

http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#associating-snippets-with-users

https://github.com/tomchristie/django-rest-framework/issues/409#issuecomment-10428031

Ammeter answered 26/3, 2014 at 19:16 Comment(2)
Mate thank you sooooo much . I knew it was simple but i dont know python.Obsessive
How can I do the same thing if I need to use UserSerializer instead of serializers.Field?Thisbee

© 2022 - 2024 — McMap. All rights reserved.