Question

I have a m2m field in a class, and a through table. I am not table to save the list of items from the through table. if i have a multi select form, like below, and i want to be able to save all the selected items, how should i do it??

My model form looks like this:

class ClassroomForm(ModelForm):
    class Meta:
          model = Classroom
          fields = ['classname','members','private']

    def __init__(self, *args, **kwargs):
                creator = kwargs.pop('user')
  super(ClassroomForm, self).__init__(*args, **kwargs)
  relations = Relations.objects.filter(initiated_by = creator)
  self.fields["members"].queryset = \
       User.objects.filter(pk__in=[r.follow.pk for r in relations])

and my save method like this:

def save_classroom(request):
   classroom_instance = Classroom()
   if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES, user = request.user) 
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user 
           new_obj.save()
           membership = Membership(member = HERE SELECTED ITEMS FROM FORM,classroom=new_obj)

           membership.save() 

How this can be done? Thanks!

Was it helpful?

Solution

Looks like you have duplicated you question. I put answer here: Django m2m form save " through " table

OTHER TIPS

Django should handle many-to-many ModelForms just as any other model form.

When you use a simple save() on a form, all data -- including many-to-many data -- is saved without the need for any additional method calls.

Reference:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top