我的 Django 管理员输入不允许我添加多个图像



我想做一个Django模型,与Django Rest框架。我希望这允许我在相同的输入中加载一个或多个图像。

:

from django.db import models
from datetime import datetime
from apps.category.models import Category
from django.conf import settings
class Product(models.Model):
code = models.CharField(max_length=255, null=True)
name = models.CharField(max_length=255)
image = models.ImageField(upload_to='photos/%Y/%m/', blank = True, null=True, default='')
description = models.TextField()
caracteristicas = models.JSONField(default=dict)
price = models.DecimalField(max_digits=6, decimal_places=2)
compare_price = models.DecimalField(max_digits=6, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
quantity = models.IntegerField(default=0)
sold = models.IntegerField(default=0)
date_created = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.name
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name = 'images')
image = models.ImageField(upload_to='photos/%Y/%m/', default="", null=True, blank=True)

序列化器:

from rest_framework import serializers
from .models import Product, ProductImage
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = ["id", "product", "image"]
class ProductSerializer(serializers.ModelSerializer):
images = ProductImageSerializer(many=True, read_only=True)
uploaded_images = serializers.ListField(
child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False),
write_only=True
)
class Meta:
model = Product
fields = [
'id',
'code',
'name',
'description',
'caracteristicas',
'price',
'compare_price',
'category',
'quantity',
'sold',
'date_created',
'images',
'uploaded_images'
]
def create(self, validated_data):
uploaded_images = validated_data.pop("uploaded_images")
product = Product.objects.create(**validated_data)
for image in uploaded_images:
newproduct_image = ProductImage.objects.create(product=product, image=image)
return product

我只是想如何使以下输入字段允许我加载多个图像:

图片参考输入

thank you very much

您没有发布您的admin.py,但我的猜测是,您还需要将您的ProductImage模型注册为inlines,因为您已经使用了ProductProductImage之间的One2Many关系:

在你的admin.py:

class ProductImageAdmin(admin.StackedInline):
model = ProductImage
class ProductAdmin(admin.ModelAdmin):
inlines = [ProductImageAdmin]
class Meta:
model = Product

admin.site.register(ProductImage)
admin.site.register(Product, ProductAdmin)

你也可以查看这个SO答案来了解更多细节。

希望有帮助:)

最新更新