【发布时间】:2021-04-13 19:14:50
【问题描述】:
我是 Django 新手。我不知道如何创建一个能正确显示我的模型的表单,它有两个ForeignKey 字段和三个ManytoManyFields。我熟悉从更简单的模型创建表单,但我被困在这个模型上。到目前为止,我已经尝试过ModelForm 并将ModelChoiceField 用于ForeignKey 关系,但这不起作用。查看表单时,字段选项未呈现。然后我尝试了 inlineformset_factory 但我找不到有用的例子。任何帮助表示赞赏。
我正在尝试为模型创建 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']
【问题讨论】:
标签: django django-models django-views django-forms django-templates