mohamed hawas
mohamed hawas

Reputation: 23

how to get id of current object

how to get current id instead of static id (7) to add image to flat

'''

class CreateFlat(CreateAPIView):
serializer_class = CreateFlat
queryset = Flat.objects.all()
permission_classes = [AllowAny]

def post(self, request, *args, **kwargs):
    print(request.data)
    my_img = request.data['id_image']
    ima = Images.objects.get(id=my_img)
    print(self.id)
    print(self)
    flat = Flat.objects.get(id=7)
    flat.images.add(ima);
    serializer = FlatSerializer(flat, many=True)
    return Response("done")
    

'''

Upvotes: 0

Views: 211

Answers (1)

larick
larick

Reputation: 168

There are so many errors but I think I can make you clear

First of all I would like to tell you about your view in general:

  • If you use CreateAPIView it using CreateModelMixin you should work with create method, not post, but it does not really matter ok.
  • In CreateAPIView there is only post method so you can remove queryset attribute
  • Keep your view class thin and add your logic in serializer, create method in serializer in this case

And finally about your question. if your path url looks like this flat/<int:pk>/add-images then try this

lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
id = self.kwargs[lookup_url_kwarg]

Upvotes: 1

Related Questions