Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework auto-populate filed with user.id

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' )
like image 275
user3418042 Avatar asked Mar 26 '14 17:03

user3418042


People also ask

How do I update user details in Django REST framework?

Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is Django Restapi?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.


1 Answers

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

like image 130
Farhan Khan Avatar answered Nov 10 '22 06:11

Farhan Khan