简体   繁体   中英

Send related image to Django Rest Framework

Hello everyone reading this post. I got such issue. So, first of all I have such models layout

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
description = models.TextField(max_length=4000, null=True)
liked_profiles = models.ManyToManyField('self', related_name='likes')
disliked_profiles = models.ManyToManyField('self', related_name='dislikes')

class Image(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='images', max_length=6)
path = models.ImageField(upload_to='profile_images')

So, I want to create a drf endpoint that will receive some kind of image, create it, and link to the profile model. But I really not sure how to implement this(I want to make it with django viewsets).

The main goal is not to provide another viewset class (like ImageViewSet), but to make it part of ProfileViewSet. So now I have such viewset (contains a method to update the description)

class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
permission_classes = (IsAuthenticated, )

@action(detail=True, methods=['PUT'])
def set_description(self, request, pk=None):
    profile = self.get_object()
    serializer = DescriptionSerializer(data=request.data)
    if serializer.is_valid():
        profile.description = request.data['description']
        profile.save()
    else:
        return Response(serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)

I want to add something like "add_image" method to it.

How can I implement it and is it actually possible(otherwise you can help me to implement it with another viewset)? I will be extremely grateful for your help

You can do sth similar to your set_description:

@action(
    detail=True,
    methods=["post"],
    serializer_class=ImageSerializer, # write your custom serializer, override save() method and save images from self.context["request"].FILES.items()
)
def create_image(self, request, pk=None):
    instance = self.get_object()
    serializer = self.get_serializer(instance, data=self.request.data)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM