我已经更改了django注册码。我在注册期间在UserProfile
和Business
模型中插入数据。
数据正在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()
感谢 更新
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 :(得分: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)
<强>更新强>
@no_access我认为将User
实例分配到ManyToManyField
中的Business
的过程中存在问题。我怀疑ManyToManyField
字段没有获得对正在创建的User
实例的引用。 intermediate
字段的ManyToManyField
表需要一个适当的User
对象来引用。所以,我认为这就是问题所在。