簡體   English   中英

如何為外鍵Django創建表單

[英]How to create forms for foreign key django

楷模,

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對象制作表格,因為它具有作為外鍵的發布。

forms.py,

class PublicationForm(forms.ModelForm):
    name = forms.CharField(max_length=128, help_text="Please enter the publication name.")
    address = forms.CharField(max_length=128, help_text="Please enter the address for publication.")
    website=forms.URLField(max_length=200, help_text="Please enter the URL of publication.")
    class Meta:
        model = 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.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.

看看這個ModelChoiceField

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

嘗試在視圖中鏈接它們。 使用save(commit = False),您將創建一個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.

當您使用ModelMultipleChoiceField ,它以形式提供Publication的查詢集,並且您在BookPublication模型之間使用外鍵關系,因此該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:

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()
                                        )
    def save(self, commit=True):
       instance = super().save(commit=False)
       pub = self.cleaned_data['publication']
       instance.publication = pub[0]
       instance.save(commit)
       return instance

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM