IntegrityError:可能不是NULL

时间:2014-07-01 01:51:10

标签: python django

我正用这个把头发拉出来。当我尝试从管理页面添加“产品”时,我遇到了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的新手。任何和所有帮助表示赞赏。

编辑:忘记提及我已将Blank = true和null = true添加到Product.img,然后使用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?

1 个答案:

答案 0 :(得分:2)

实际上您需要在img字段中添加null=True,因此请将其设为img = models.ImageField(upload_to='images', blank=True, null=True)。 不同之处在于,因为blank=True决定表单是否需要字段。 blank=False表示该字段不能为空,blank=True表示不需要字段。 关于null=True在数据库的列中设置NULL,这将解决您的问题。

相关问题