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.
models.py
class Animal(models.Model): name = models.CharField(max_length=500, blank=False, null=False) **type = 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): type = 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 = ['type', 'ageGroup', 'breed', 'breedGroup'] https://stackoverflow.com/questions/65622918/how-to-create-a-form-in-django-from-a-model-with-multiple-foreignkey-and-manytom January 08, 2021 at 11:07AM
没有评论:
发表评论