如何为外键djang创建窗体

2024-04-27 22:42:06 发布

您现在位置:Python中文网/ 问答频道 /正文

模型

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.

Tags: the对象nameself表单modelsformslength
3条回答

尝试在视图中链接它们。使用save(commit=False)可以创建一个等待完成数据的Book对象。完成book对象后,可以将其与所有外键一起保存

if request.method == 'POST':
    bf = BookForm(request.POST)
    publication_id = request.POST.get('publication_id',0)
    if bf.is_valid():
        if publication_id:
            book = bf.save(commit=False)
            book.publication_id = publication_id
            book.save()
        else:
            # functional error.
    else:
        # functional  error.

看看这个ModelChoiceField

publication = forms.ModelChoiceField(queryset=Book.objects.all())

当您使用ModelMultipleChoiceField时,它在form中给出了一个Publication的查询集,并且您在Book和{}模型之间使用foreignkey关系,因此modelform无法保存publication,因为它没有得到publication对象。所以你可以这样做来解决这个问题:

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.ChoiceField(
        choices=[(x.id,x.name) for x in Publication.objects.all()]
         )

    def save(self, commit=True):
      instance = super().save(commit=False)
      pub = self.cleaned_data['publication']
      instance.publication = Publication.objects.get(pk=pub)
      instance.save(commit)
      return instance


    class Meta:
        model = Book
        fields = ('name', 'author','slug')

或者您可以像这样使用ModelMultipleChoiceField:

^{pr2}$

相关问题 更多 >