python - 在 json 上上传图像 DJANGO REST FRAMEWORK

标签 python json django django-rest-framework

当我为我的应用程序注册新用户时,我尝试上传编码的 BASE64 图像,我在用户配置文件中使用 ImageField 问题是 API 给了我以下错误。

{
  "userprofile": {
    "photo": [
      "The submitted data was not a file. Check the encoding type on the form."
    ]
  }
}

这是我在请求中的信息我使用带有 header Content-Type: application/json 的 POST 请求作为请求我使用来自 google 的 POSTMAN

{

    "username": "is690002",
    "password": "is690002",
    "first_name": "andres ",
    "last_name": "Barragan",
    "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef958e9b9a9d8095c1828e9d8c80af88828e8683c18c8082" rel="noreferrer noopener nofollow">[email protected]</a>",
    "userprofile": {
        "gender": "F",
        "phone_number": "3315854644",
        "photo": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYAB......."
    }
  }

这是我的模型.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')

    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M')

    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',message="Phone must be entered in the format: '+999999999'. Up 15 digits allowed.")
    #The Field on DataBase after check if it's a valid Phone Number.
    # validators should be a list
    phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True) 
    photo = models.ImageField(upload_to = 'C:\ProjectsDJ\carpoolapp\photos', null = True)

我的序列化器

class UserProfileSerializer(serializers.ModelSerializer):
    photo =  serializers.ImageField(max_length=None, use_url=False)
    class Meta:
        model = UserProfile
        fields = (
            'gender',
            'phone_number',
            'photo'
            )


class UserRegistrationSerializer(serializers.HyperlinkedModelSerializer):
    userprofile = UserProfileSerializer()
    class Meta:
        model = User
        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password',
            'userprofile'
            )
        extra_kwargs = {'password': {'write_only': True}}

#@Override create for create a user and profile from HTTP Request
    def create(self, validated_data): #
            userprofile_data = validated_data.pop('userprofile')
            user = User.objects.create(**validated_data) # Create the user object instance before store in the DB
            user.set_password(validated_data['password']) #Hash to the Password of the user instance
            user.save() #Save the Hashed Password
            UserProfile.objects.create(user=user, **userprofile_data)
            return user #Return user object

和我的 View.py

class UserRegister(APIView):

    permission_classes = ()
    def post(self, request):
        serializer = UserRegistrationSerializer(data = request.data) #, files = request.FILES)
        serializer.is_valid(raise_exception=True) # If the JSON Is
        serializer.save() #Save user in DB
        return Response(status=status.HTTP_201_CREATED)

注意:如果我不使用 imageField,一切都很好,我可以创建我的用户等,我还在 StackOverflow 中尝试了两个教程

最佳答案

Django REST 框架不支持通过 JSON 上传开箱即用的文件。 The documentation mentions that 。也许第三方可以。

请注意,DRF 中的文件上传测试确实使用表单内容类型而不是 JSON。

关于python - 在 json 上上传图像 DJANGO REST FRAMEWORK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322778/

相关文章:

Python Scrape with requests 和 beautifulsoup

python - 声明 Pydantic 模型 "TypeError: ' 类型的对象不可迭代”

javascript - 使用 JQuery/Ajax 将我的 API 连接到 HTML

django - PyCharm 2.5 TestRunner 无法导入特定模块

python - 在 django admin 上使用 list_editable 时不显示文本字段

python - 如何从抽象基类覆盖模型字段的默认值

python - 简单强化学习算法的损失函数

python - 您更喜欢使用 del 还是重新分配给 None(垃圾收集)

java - 导入库在 Play Framework 中出现错误

json - 如何使用嵌套字典反序列化 json?