Обновление APIView в Django не обновляет поле изображения - PullRequest
0 голосов
/ 07 июня 2019

В проекте Django у меня есть простое обновление APIView

class ProfileUpdateAPIView(UpdateAPIView):
    serializer_class = ProfileUpdateSerializer
    authentication_classes = ( CsrfExemptSessionAuthentication, BasicAuthentication, TokenAuthentication,)
    permission_classes = ((IsAuthenticated,))

и простая модель

def image_upload_fun(instance, filename):
    return 'profile_pics/user_{0}.{1}'.format(str(instance.phone_number),filename.split(".")[1])

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True)
    profile_pic = models.ImageField(upload_to=image_upload_fun, null=True, blank=True)
    phone_number = models.CharField(max_length=12, unique=True, null=False, blank=False)

This is how I hit request from postman

Он не создает новый файл и не обновляет profile_pic_field. Хотя через панель администратора он (изображение) легко обновляется или создается


Мой запрос на звонок

Заголовки:

Authorization:Token 7554057effce1fcbc313f9a96be99ae17efb8eaf

Тело:

phone_number:92123123132
profile_pic :[[my file]]

serializers.py

class ProfileUpdateSerializer(serializers.ModelSerializer):
    profile_pic_url = serializers.SerializerMethodField()

    class Meta:
        model = Profile
        fields = ["name", "email", "phone_number","gender", "date_of_birth", "profile_pic_url"]

    def get_profile_pic_url(self, obj):
        try:
            return self.context["request"].build_absolute_uri("/").strip("/")+str(obj.profile_pic.url)
        except Exception as E:
            print(E)
            return str("")

Ответы [ 2 ]

1 голос
/ 07 июня 2019

По умолчанию django-rest-framework использует JSONParsor.Он не будет анализировать загруженные файлы.Для разбора файлов мы должны использовать MultiPartParser и FormParser, как показано ниже

from rest_framework.parsers import MultiPartParser, FormParser


class ProfileUpdateAPIView(UpdateAPIView):
    serializer_class = ProfileUpdateSerializer
    authentication_classes = (
        CsrfExemptSessionAuthentication,
        BasicAuthentication,
        TokenAuthentication
    )
    permission_classes = (IsAuthenticated,)
    parser_classes = (MultiPartParser, FormParser)

Запрос с использованием запросов Python

import requests

headers = {
  "Content-Type": "multipart/form-data",
  "Authorization": "Token <your token>"
}
data = {
    "phone_number": "987654231",
    "profile_pic": open("path/to/image.png", "r").read()
}

r = requests.post("http://localhost:8000/api/end-point/", data=data, headers=headers)
print(r.json())
0 голосов
/ 07 июня 2019

Я сделал ошибку при определении полей ProfileUpdateSerializer

Я не включил поле profile_pic в поля сериализатора

Редактирование сериализатора для добавления поля "profile_pic" для загрузки изображения

class ProfileUpdateSerializer(serializers.ModelSerializer):
    profile_pic_url = serializers.SerializerMethodField()

    class Meta:
        model = Profile
        fields = ["name", "email", "phone_number","gender", "date_of_birth", "profile_pic","profile_pic_url"]

    def get_profile_pic_url(self, obj):
        try:
            return self.context["request"].build_absolute_uri("/").strip("/")+str(obj.profile_pic.url)
        except Exception as E:
            print(E)
            return str("")

Я думал, что сериализатор просто использовался, чтобы показать ответ после обновления.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...