【问题标题】:IntegrityError: may not be NULLIntegrityError:不能为 NULL
【发布时间】: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

标签: python django


【解决方案1】:

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

【讨论】:

  • 添加 blank=True 就足够了 - ImageField 的底层实现是 CharField,建议不要对 CharFields 使用 null=True。
  • 我已尝试删除空白=True 并添加 null=True。我已经尝试添加两者。我迁移了数据库,但仍然无法正常工作。我真的很想让它工作,而不必删除我的数据库并从头开始。
  • 你能用 phpmyadmin 访问数据库吗?如果可能,您需要手动从数据库中删除 not null 约束。看看是否有效
  • 无论出于何种原因,这就是问题所在。太感谢了!只需运行架构以从 Product 表中删除 img 字段,现在它可以完美运行了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
相关资源
最近更新 更多