Django Form with a one-to-many relationship

Sounds like you want an inline model form. This give you the ability to add/remove Car objects from a Person within the Person form.

That previous link was for inlinemodeladmin. This next link is for an inline form: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelforms-factory


I didn't have any chance with inline formset, so i would suggest to override your save method of the model, i feel it's more DRY:

class PersonForm(forms.ModelForm):
    # add a field to select a car
    car = forms.ModelChoiceField(car.objects.all())

    class Meta:
        model = Person
        fields = ('description', 'car')

     def save(self, commit=True):
        instance = super().save(commit)
        # set Car reverse foreign key from the Person model
        instance.car_set.add(self.cleaned_data['car']))
        return instance

I know this is an old thread, but since I found myself almost exclusively pointed here by google when searching, I thought I would include the following for anyone else looking for an answer.

The answer, I think, is to use

https://docs.djangoproject.com/en/3.1/ref/forms/fields/#modelchoicefield

or

https://docs.djangoproject.com/en/3.1/ref/forms/fields/#modelmultiplechoicefield

There is a good article on how to use the modelmultiplechoicefield at :

https://medium.com/swlh/django-forms-for-many-to-many-fields-d977dec4b024

But it works for one to many fields as well. These allow us to generate a form with multiple choices as checkboxes or similar widgets based upon a related field in a model.