Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-Rest-Framework: How to post to foreignkey field using request.user for logged in user

I am using Django rest Framework to make an api to be consumed by an android app. I have a model for events and Venue:

  class Event(models.Model):
     user=models.ForeignKey(User,related_name="%(class)s")
     title=models.CharField(max_length=256)
     venue=models.ForeignKey(Venue,related_name="%(class)s_venue")
     description=models.CharField(max_length=256)
     time=models.DateTimeField(max_length=256)
     event_pic=models.ImageField(upload_to="photos/event_pic/%Y/%m/%d",null=True,blank=True)

     album=models.ForeignKey(Album,null=True,blank=True,related_name="%(class)s_album")
     photo=models.ForeignKey(Photo,null=True,blank=True,related_name="%(class)s_photo")

     likes=GenericRelation(Like,null=True,blank=True)
     comments=GenericRelation(Comments,null=True,blank=True)

Here is my Venue model.

class Venue(models.Model):
     name=models.CharField(max_length=256)
     longitude=models.FloatField(null=True,blank=True)
     latitude=models.FloatField(null=True,blank=True)

     def __unicode__(self):
         return self.name

I would like to post to the user field using request.user and the venue field using name.Is it possible to do this and if so how do I do it. Here are the serializers and views.

class WeddingList(generics.ListCreateAPIView):    

     queryset=Wedding.objects.all()
     serializer_class=WeddingSerializer


class WeddingDetail(generics.RetrieveUpdateDestroyAPIView):
     queryset=Wedding.objects.all()
     serializer_class=WeddingSerializer





class VenueList(generics.ListCreateAPIView):
     queryset=Venue.objects.all()
     serializer_class=VenueSerializer

class VenueDetail(generics.RetrieveUpdateDestroyAPIView):
     queryset=Venue.objects.all()
     serializer_class=VenueSerializer

class VenueSerializer(serializers.ModelSerializer):
      class Meta:
           model=Venue
           fields=('name')

class WeddingSerializer(serializers.ModelSerializer):


      class Meta:
           model = Wedding
           excludes=('id',)
like image 659
zacmwa Avatar asked Aug 27 '14 11:08

zacmwa


1 Answers

Since Django REST Framework 3, the pre_save hook is not available anymore. Instead, override perform_create:

def perform_create(self, serializer):
    serializer.save(user=self.request.user, ...)
like image 122
Danilo Bargen Avatar answered Oct 04 '22 15:10

Danilo Bargen