Saving a Django form with a Many2Many field with through table

Posted by PhilGo20 on Stack Overflow See other posts from Stack Overflow or by PhilGo20
Published on 2010-06-12T17:46:09Z Indexed on 2010/06/12 17:53 UTC
Read the original article Hit count: 200

So I have this model with multiple Many2Many relationship. 2 of those (EventCategorizing and EventLocation are through tables/intermediary models)

class Event(models.Model):
""" Event information for Way-finding and Navigator application"""

categories = models.ManyToManyField('EventCategorizing', null=True, blank=True, help_text="categories associated with the location") #categories associated with the location
images = models.ManyToManyField(KMSImageP, null=True, blank=True) #images related to the event
creator = models.ForeignKey(User, verbose_name=_('creator'), related_name="%(class)s_created")
locations = models.ManyToManyField('EventLocation', null=True, blank=True)

In my view, I first need to save the creator as the request user, so I use the commit=False parameter to get the form values.

if event_form.is_valid():
    event = event_form.save(commit=False)
    #we save the request user as the creator
    event.creator = request.user
    event.save()
    event = event_form.save_m2m()
    event.save()

I get the following error:

*** TypeError: 'EventCategorizing' instance expected

I can manually add the M2M relationship to my "event" instance, but I am sure there is a simpler way. Am I missing on something ?

© Stack Overflow or respective owner

Related posts about python

Related posts about best-practices