我有一个名为Product
的Django模型。我想在Product
中添加1:n关系来选择其产品的图片,并在Product
管理员表单上,我希望该用户添加图片。
我尝试了ManyToMany
关系,但这并不是我想要的,因为我不希望用户访问两个表单Product
来创建产品,Images
来创建图像然后Products
再次选择Product
将拥有的图片。
任何人都有想法吗?对不起,如果我不清楚,如果您需要更多信息,请告诉我。
models.py :
class Image(models.Model):
""" Generic image model
"""
name = models.CharField(max_length=100, blank=False, verbose_name=_("name"))
image_file = models.ImageField(blank=False, upload_to=image_upload, verbose_name=_("file"))
def __unicode__(self):
return u'{}'.format(self.name)
def post_url(self):
return os.path.join(settings.MEDIA_ROOT, 'images', self.__class__.__name__)
class Meta:
verbose_name=_("Image")
verbose_name_plural=_("Images")
class Product(models.Model):
name = models.CharField(max_length=100, blank=False, unique=True, verbose_name=_("name"))
creation_date = models.DateField(auto_now_add=True, blank=False, db_index=True, verbose_name=_("date"))
cover_image = models.ImageField(blank=False, upload_to=product_cover_upload,verbose_name=_("image"))
category = models.ForeignKey(Category, blank=True,verbose_name=_("category"))
value = models.DecimalField(blank=False, max_digits=15, decimal_places=2,verbose_name=_("value"))
featured = models.BooleanField(blank=False, default=False,verbose_name=_("featured"))
def __unicode__(self):
return u'{}'.format(self.name)
class Meta:
ordering = ['name']
verbose_name=_("product")
verbose_name_plural=_("products")
class ProductImage(Image):
""" Product images
"""
product = models.ForeignKey(Product,verbose_name=_("product"))
def post_url(self):
return os.path.join(settings.MEDIA_ROOT, 'images', 'products', str(self.product))
class Meta:
proxy = False
verbose_name=_("product image")
verbose_name_plural=_("products images")
admin.py :
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'creation_date', 'category', 'value', 'featured',)
read_only_fields = ('creation_date',)
admin.site.register(Product, ProductAdmin)
答案 0 :(得分:1)
admin.py:
class ProductImageInline(admin.StackedInline):
model = ProductImage
class GalleryAdmin(admin.ModelAdmin):
inlines = [ProductImageInline]