模型
class Publication(models.Model):
name=models.CharField(max_length=128)
address=models.CharField(max_length=500)
website=models.URLField()
def __unicode__(self):
return self.name
class Book(models.Model):
name=models.CharField(max_length=128)
publication=models.ForeignKey(Publication)
author=models.CharField(max_length=128)
slug=models.SlugField(unique=True)
def __unicode__(self):
return self.name
def save(self,*args,**kwagrs):
self.slug=slugify(self.slug)
super(Book,self).save(*args,**kwagrs)
我试图为发布对象制作窗体。效果很好。但我不可能为Book对象创建表单,因为它的发布是作为外键的。在
在表单.py你说
^{pr2}$如何为以publication作为外键的book对象创建表单。在
更新
我试过把书的对象
class BookForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the name.")
author = forms.CharField(max_length=128, help_text="Please enter the name of the autthor.")
slug = forms.SlugField(help_text="Please enter the slug")
publication = forms.ModelMultipleChoiceField(
queryset=Publication.objects.all()
)
class Meta:
model = Book
fields = ('name', 'author','slug','publication')
但当我提交表单时,它会在下面抛出错误
Cannot assign "[<Publication: C# in Depth>]": "Book.publication" must be a "Publication" instance.
尝试在视图中链接它们。使用save(commit=False)可以创建一个等待完成数据的Book对象。完成book对象后,可以将其与所有外键一起保存
看看这个ModelChoiceField
当您使用}模型之间使用foreignkey关系,因此modelform无法保存
ModelMultipleChoiceField
时,它在form中给出了一个Publication
的查询集,并且您在Book
和{publication
,因为它没有得到publication
对象。所以你可以这样做来解决这个问题:或者您可以像这样使用ModelMultipleChoiceField:
^{pr2}$相关问题 更多 >
编程相关推荐