views:

34

answers:

2

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!

A: 

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:

The MYYN
i have to save data in the intermediary 'through' table. That's why i am trying to initialise it. Otherwise, i get an error like: Cannot set values on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
dana
+1  A: 

Looks like you have duplicated you question. I put answer here: http://stackoverflow.com/questions/3074938/django-m2m-form-save-through-table/3125398#3125398

Lukasz Dziedzia
i've seen and accepted it! thas is what i was looking for.Thnks!
dana