【问题标题】:How to display select (manytomany) as thumbnails?如何将选择(manytomany)显示为缩略图?
【发布时间】:2015-11-12 09:51:04
【问题描述】:

我有模型:

class ProductImage(models.Model):
    image = models.ImageField(upload_to="product/", null=True, blank=True)
    name = models.CharField(max_length=255)
    [...]

class Product(models.Model):
    name = models.CharField(max_length=255)
    decsription = models.TextField(blank=True, null=True)
    images = models.ManyToManyField(ProductImage, blank=True, null=True)
    [...]

我想将多选(在管理员的编辑产品页面上)显示为带有名称的缩略图。怎么做?

【问题讨论】:

  • “多选”是什么意思?

标签: django django-admin


【解决方案1】:

我的解决方法,在管理员中:

class ProductForm(forms.ModelForm):

    class Meta:
        model = Product

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)

        images = ProductImage.objects.all()
        items = []
        for image in images:
            items.append(
                (image.pk, mark_safe('%s' % image.image.url))
            )
        self.fields['images'].choices = items

class ProductAdmin(ModelAdmin):
    form = ProductForm

site.register(Product, ProductAdmin)

并覆盖 base.html:

jQuery(function(){
    jQuery('#id_images').css('width', '400px').css('height', '400px');
    jQuery('#id_images option').each(function(){
        jQuery(this).attr('style', 'background: url('+jQuery(this).text()+') no-repeat; background-size: 70px 70px; height: 80px; padding-left: 80px; line-height: 80px;');
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 2023-03-31
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多