完整性错误:不能为空
我快要抓狂了。当我尝试从管理页面添加一个“产品”时,出现了一个错误:IntegrityError: main_product.img 不能为 NULL。
Models.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
但错误依然存在。如果我想在我的Products模型里添加img字段,我该如何在管理面板中添加多个图片呢?
1 个回答
2
其实你需要在图片字段里加上 null=True
,所以应该写成 img = models.ImageField(upload_to='images', blank=True, null=True)
。这里的区别在于,blank=True
决定了这个字段在表单中是否是必填的。blank=False
表示这个字段不能留空,而 blank=True
则表示这个字段可以不填。至于 null=True
是用来在数据库的这一列里设置为 NULL,这样就能解决你的问题了。