Edit the opposite side of a many to many relationship with django generic form

Posted by Ed on Stack Overflow See other posts from Stack Overflow or by Ed
Published on 2010-03-31T00:34:31Z Indexed on 2010/04/11 13:23 UTC
Read the original article Hit count: 311

Filed under:
|
|
|
|

I have two models:

 class Actor(models.Model):
     name = models.CharField(max_length=30, unique = True)
     event = models.ManyToManyField(Event, blank=True, null=True)

 class Event(models.Model):
     name = models.CharField(max_length=30, unique = True)
     long_description = models.TextField(blank=True, null=True)

In a previous question: http://stackoverflow.com/questions/2503243/django-form-linking-2-models-by-many-to-many-field, I created an EventForm with a save function:

class EventForm(forms.ModelForm):
      class Meta:
            model = Event

      def save(self, commit=True):
            instance = forms.ModelForm.save(self)
            instance.actors_set.clear()
            for actor in self.cleaned_data['actors']:
                instance.actors_set.add(actors)
            return instance

This allowed me to add m2m links from the other side of the defined m2m connection.

Now I want to edit the entry. I've been using a generic function:

def generic_edit(request, modelname, object_id):
       modelname = modelname.lower()
       form_class = form_dict[modelname]
       return update_object(request,
            form_class = form_class,
            object_id = object_id,
            template_name = 'createdit.html'
       )

but this pulls in all the info except the many-to-many selections saved to this object.

I think I need to do something similar to this: http://stackoverflow.com/questions/1700202/editing-both-sides-of-m2m-in-admin-page, but I haven't figured it out.

How do I use the generic update_object to edit the other side of many-to-many link?

© Stack Overflow or respective owner

Related posts about django

Related posts about forms