【发布时间】:2014-07-01 01:51:10
【问题描述】:
我正在用这个把头发拉出来。当我尝试从管理页面添加“产品”时,我收到 IntegrityError: main_product.img may not be NULL.
模型.py
class Product(models.Model):
name = models.CharField(max_length=500)
short = models.CharField(max_length=250)
description = models.TextField()
price = models.DecimalField(max_digits=8, decimal_places=2)
in_stock = models.BooleanField()
def __unicode__(self):
return self.name
class ProductImages(models.Model):
product = models.ForeignKey(Product, blank=True)
img = models.ImageField(upload_to='images', blank=True)
caption = models.CharField(max_length=300, blank=True)
class ProductFeatures(models.Model):
product = models.ForeignKey(Product)
feature = models.CharField(max_length=500)
Admin.py
class ProductFeaturesAdmin(admin.TabularInline):
model = ProductFeatures
extra = 1
class ProductImageAdmin(admin.TabularInline):
model = ProductImages
extra = 1
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'in_stock')
inlines = [ProductFeaturesAdmin, ProductImageAdmin]
admin.site.register(Product,ProductAdmin)
我在上传时使用 Pillow 来调整图像大小,所以我的 ProductImages 模型中有一个自定义的 save() 函数。我认为这是问题所在,但它仍然无法正常工作。如您所知,我对 Django 和 Python 真的很陌生。任何和所有的帮助表示赞赏。
编辑:忘了说我在 Product.img 中添加了 blank=true 和 null=true,然后使用 South 迁移表。
编辑 2:这是我的新 ProductImages 模型。
class ProductImages(models.Model):
product = models.ForeignKey(Product)
img = models.ImageField(upload_to='images', blank=True, null=True)
caption = models.CharField(max_length=300, blank=True)
我用 South 跑了:
python manage.py schemamigration main --auto
python manage.py migrate main
仍然有错误。如果我要将 img 字段添加到我的 Products 模型中,我如何能够在管理面板中添加多个 img?
【问题讨论】:
-
我在
Product模型中看不到img。 -
将 ProductImages 链接到 Product,ProductImages.img 不会变成 Product.img 吗?
-
img 应该是 Product 中的直接属性,否则会类似于 main_productimages.img。疯狂的猜测是,您最初在 Product 模型中有 img,后来将其更改为单独的模型,但没有进行数据库迁移。
-
我没有看到具有 null = True 的 img 字段。如果 null 未设置为 true,则该字段必须具有值才能成功保存对象。 docs.djangoproject.com/en/dev/ref/models/fields/#null