2012-01-26 22 views
0

我已經更改了django註冊碼。我在註冊期間在UserProfileBusiness模型中插入數據。 數據保存在UserProfile型號。「商業」實例在可以使用多對多關係之前需要具有主鍵值

#TODO: saving contact and address field data into UserProfile 
user_profile = new_user.get_profile() 
user_profile.user = new_user 
user_profile.contact, user_profile.address = contact, kwargs['address'] 
user_profile.save() 

以下代碼無法正常工作。獲取此錯誤。 'Business' instance needs to have a primary key value before a many-to-many relationship can be used.

#TODO: saving business field data into Business Model 
user_business = Business() 
user_business.owner = new_user 
user_business.name = business 
user_business.save() 

感謝 UPDATE

class Business(models.Model): 
name = models.CharField(max_length=100) 
slug = models.SlugField(max_length=100) 
owner = models.ManyToManyField(User) 
created = models.DateTimeField(editable=False, default=datetime.now) 
modified = models.DateTimeField(editable=False, default=datetime.now) 

class Meta: 
    ordering = ['name'] 

def save(self): 
    self.modified = datetime.now() 
    if not self.slug: 
     self.slug = slugify(self.name, instance=self) 
    super(Business, self).save() 
+0

你能不能請示模型結構。 –

+0

我認爲自定義保存方法存在問題。但是,我不確定(仍在調查)。你可以嘗試刪除它並運行你的代碼。 –

+0

什麼信號被稱爲'商業'?請張貼任何和全部。 –

回答

1

嘗試更新你的自定義代碼:

def save(self, *args, **kwargs): 
    self.modified = datetime.now() 
    if not self.slug: 
     self.slug = slugify(self.name) 
    super(Business, self).save(*args, **kwargs) 

UPDATE

@no_access我覺得在將User實例分配給Business中的ManyToManyField的過程中,re是一個問題。我懷疑ManyToManyField字段沒有得到正在創建的User實例的引用。 intermediate表的ManyToManyField字段需要合適的User對象才能參考。所以,我認爲這是問題所在。

+0

自定義保存方法沒有問題。我也嘗試過你的方法。但沒有運氣。 – Kulbir

+1

@no_access可能沒有解決你的問題,但你需要用這種方法覆蓋'save'(即用'* args'和'** kwargs')。否則,你會在Django中打破一堆調用保存在模型中的其他東西(尤其是管理員)。 –

+0

@no_access首先,你有沒有爲slugify編寫自定義代碼?如果你使用了默認的,你不需要提供'instance = self'。 其次,根據問題中的「Chris Pratt」的註釋,您不需要在模型更改後放置'self.modified = datetime.now()'語句。 最後,這是與「商業」模型相關的完整代碼嗎? –

相關問題