簡體   English   中英

如何從具有多個 ForeignKey 和 ManytoManyField 字段的 model 在 Django 中創建表單?

[英]How to create a form in Django from a model with multiple ForeignKey and ManytoManyField fields?

我是 Django 新手。 我無法弄清楚如何創建一個正確顯示我的 model 的表單,它有兩個ForeignKey字段和三個ManytoManyFields 我熟悉從更簡單的模型創建 forms ,但我堅持這個。 到目前為止,我已經嘗試過ModelForm並將ModelChoiceField用於ForeignKey關系,但這不起作用。 查看表單時,字段選項未呈現。 然后我嘗試了 inlineformset_factory 但我找不到有用的例子。 任何幫助表示贊賞。 我正在嘗試為 model 創建 CreateView、UpdateView 和 DeleteView 選項。

models.py

    class Animal(models.Model):
        name = models.CharField(max_length=500, blank=False, null=False)
        **atype = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True)**
        **ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True)**
        ageYears = models.PositiveIntegerField(blank=False, null=False)
        ageMonths = models.PositiveIntegerField(blank=True, null=True)
        sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA')
        city = models.CharField(max_length=200, blank=True, null=True)
        state = models.CharField(max_length=200, blank=True, null=True)
        country = models.CharField(max_length=250, blank=True, null=True)
        **breedGroup = models.ManyToManyField(BreedGroup, blank=False)**
        **breed = models.ManyToManyField(Breed, blank=False)**
        tagLine = models.CharField(max_length=300, blank=False, null=False)
        goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information')
        goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information')
        goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information')
        profilePic = ResizedImageField(size=[300, 450], quality=100, upload_to='media/', default='', null=True, blank=True, keep_meta=False)
        **contact = models.ForeignKey(ContactDetails, on_delete=models.SET_NULL, blank=False, null=True)**

forms.py

    class AnimalDetailsForm(ModelForm):
        ftype = ModelChoiceField(queryset=Type.objects.all())         #doesn't work
        ageGroup = ModelChoiceField(queryset=AgeGroup.objects.all()) #doesn't work
        #breed = what method to use?
        #breedGroup = what method to use? 

        class Meta:
            model = Animal
            exclude = ['ftype', 'ageGroup', 'breed', 'breedGroup']

同樣在表單的元中,您排除了您嘗試獲取數據的字段。 應該說

class Meta:
        model = Animal
        fields = ['type', 'ageGroup', 'breed', 'breedGroup']

查閱的文檔: https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/ https://docs.djangoproject.com/en/3.1/ref/models/fields/

**編輯,刪除關於使用類型作為變量名的評論。

暫無
暫無

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

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