带有管理模型中图像的内联模型

时间:2017-02-20 15:09:53

标签: python django django-admin

我现在有两个型号的产品和产品图片我想用一个表格从管理员添加产品和图片

产品型号

class Products(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)
    description = models.TextField(null=True)
    category = models.ForeignKey(ProductCategory, null=True, blank=True)
    business = models.ForeignKey(BpBasic, default=BpBasic.get_admin_business().bp_id)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(default=None, null=True)
    created_by = models.ForeignKey(User, null=False, blank=False, related_name='product_created_by')
    updated_by = models.ForeignKey(User, null=True, blank=False, related_name='product_updated_by')

产品图片型号

class ProductImage(models.Model):
    product = models.ForeignKey(Products, null=False, on_delete=models.CASCADE, related_name='product')
    image = models.ImageField(upload_to='media/products/')
    primary = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(default=None, null=True)
    created_by = models.ForeignKey(User, null=False, blank=False, related_name='prod_image_created_by')
    updated_by = models.ForeignKey(User, null=True, blank=False, related_name='prod_image_updated_by')

产品图像内嵌模型

class ProductImageInline(admin.StackedInline):
    model = ProductImage
    exclude = ('created_at', 'updated_at', 'created_by', 'updated_by')
    extra = 1

产品管理模型

class ProductAdmin(admin.ModelAdmin):
    model = Products
    list_display = ('name', 'description', 'category')
    fieldsets = [
        ('Product Details', {'fields': ['name', 'description']}),
        ('Product Category', {'fields': ['category']})
    ]
    inlines = [ProductImageInline]

    def save_formset(self, request, form, formset, change):
        def set_user(instance):
            if not change:
                instance.created_by = request.user
            else:
                instance.updated_by = request.user
            instance.save()
        print formset
        instances = formset.save(commit=False)
        print list(instances)
        map(set_user, instances)
        instances.save()
        return instances

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
            obj.business = request.user.profile.business
        else:
            obj.updated_by = request.user
        obj.save()
        return obj

所以我在保存产品时遇到了问题

coercing to Unicode: need string or buffer, ImageFieldFile found

我收到上述文件保存错误。请帮忙!

我已成功生成的管理员界面 enter image description here

1 个答案:

答案 0 :(得分:0)

在某些模型中,您似乎遇到了__unicode__方法(或__str__,如果您使用python3)的问题。它是模型的字符串表示的特殊方法,因此它应该返回一个字符串 例如:

class ProductImage(models.Model):
    ...
    def __unicode__(self):
        return 'Image created at {}'.format(self.created_at)