Skip to content
Advertisement

Django: populating many to many field using modelformset_factory

I try to populate a many-to-many field. The Relationship exists between the Menus and Course Model. I added some custom fields to the M2M Table, so I can store the order of the courses and their type (i.e. Starter, Appetizer, etc.).

To get a dynamic webform, I use modelformset_factory with the python-formset-js-improved pip package (https://pypi.org/project/django-formset-js-improved/).

following the logic in my views.py, explained here Populate a ManyToManyField, I run into the following error. This error applies to all keyword arguments.

JavaScript

What did I get wrong? below are extracts from models.py, forms.py, views.py and the html file

EDIT I followed the documentation and tried to populate the m2m table accordingly. https://docs.djangoproject.com/en/4.0/topics/db/models/#intermediary-manytomany

I tried to add the values to the model using, but I don’t know how to access the course_type field of the menu_item_form, as I cannot validate the form:

JavaScript

models.py

JavaScript

forms.py

JavaScript

views.py

JavaScript

html

JavaScript

Advertisement

Answer

Based on this thread (Set form field value before is_valid()) I solved my problem.

I added the field course_type to the course_formset. I retrieved the data from request.POST itself.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement