I'm working on an API to use for an iPhone app. In order to like a picture, I'm assuming I need to embed a url in my serializer that can be used to add a like to a photo. Could someone please help me implement this?
I am able to view the url, but I'm not sure how to pass the photo's id to the view. This is where I've gotten so far:
views.py:
@api_view(['POST'])
def like_create_api(request, photo_id):
serializer = PhotoSerializer(data=request.DATA)
if serializer.is_valid():
serializer.object.content_object = get_object_or_404(Photo, id=photo_id)
serializer.object.likers.add(request.user)
serializer.save()
return RestResponse(serializer.data, status=status.HTTP_201_CREATED)
return RestResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py:
class PhotoSerializer(serializers.ModelSerializer):
likers = serializers.HyperlinkedRelatedField(
many=True, view_name='user_account_detail_api', read_only=True,
lookup_field='username')
like_url = LikeUrlField("like_create_api")
class Meta:
model = Photo
fields = ['like_url', 'id', 'slug', 'photo', 'likers']
models.py:
class Photo(HashtagMixin, TimeStampedModel):
category = models.ForeignKey("Category")
creator = models.ForeignKey(settings.AUTH_USER_MODEL)
likers = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='likers', blank=True)
photo = models.ImageField(upload_to=upload_location)
slug = models.SlugField()
class Meta:
app_label = 'photos'
def __unicode__(self):
return u"{}".format(self.slug)
urls.py:
url(r'^like/$', 'api.views.like_create_api',
name='like_create_api'),
Any help is appreciated. Thank you in advance!