2014-07-01 31 views
1

我正在用這個拉我的頭髮。當我嘗試從我的管理頁面添加「產品」時,我收到一個IntegrityError:main_product.img可能不是NULL。IntegrityError:可能不是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) 

我用枕頭被上傳時,調整圖像,所以我有一個自定義的保存在我的ProductImages模型()函數。我刪除了認爲這是問題,但它仍然無法正常工作。如你所知,我對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) 

我用南就跑:

python manage.py schemamigration main --auto 
python manage.py migrate main 

仍然有錯誤。如果我要將img字段添加到我的產品模型中,我將如何在管理面板中添加多個imgs?

+0

我在'產品'模型中看不到'img'。 – furas

+0

隨着ProductImages鏈接到產品,ProductImages.img不會成爲Product.img嗎? –

+0

img應該是產品中的直接屬性,否則就像main_productimages.img。瘋狂的猜測是你最初在產品模型中有img,將它改爲單獨的模型,但沒有做數據庫遷移。 – jtiai

回答

2

其實你需要在img字段中加上null=True,所以把它做成img = models.ImageField(upload_to='images', blank=True, null=True)。 區別在於blank=True決定字段是否會被表單需要。 blank=False表示該字段不能爲空,並且blank=True表示不需要字段。 關於null=True在您的數據庫的列中設置NULL將解決您的問題。

+0

添加blank = True就足夠了 - ImageField的底層實現是CharField,並且建議不要對CharField使用null = True。 – jtiai

+0

我試着刪除blank = True並添加null = True。我試過添加兩個。我遷移了數據庫,但仍然無法實現。我非常希望能夠在不刪除數據庫的情況下重新開始工作。 –

+0

你可以用phpmyadmin訪問數據庫嗎?如果可能的話,你需要手動從數據庫中刪除'not null'約束。看看是否有效 –

相關問題