I am a Django newbie. I cannot figure out how to create a form that properly displays my model, which has two ForeignKey
fields and three ManytoManyFields
. I am familiar with creating forms from more simple models, but I'm stuck on this one. So far, I've tried ModelForm
and used ModelChoiceField
for ForeignKey
relationships, but that did not work. When viewing the form, the fields options did not render. I then tried inlineformset_factory but I could not find helpful examples. Any help is appreciated.
I am trying to create CreateView, UpdateView, and DeleteView options for the model.
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']
question from:
https://stackoverflow.com/questions/65622918/how-to-create-a-form-in-django-from-a-model-with-multiple-foreignkey-and-manytom