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 after "event = event_form.save_m2m()"
*** TypeError: 'EventCategorizing' instance expected
The form is
class EventForm(forms.ModelForm):
def __init__(self,user,*args,**kwargs):
super(EventForm,self ).__init__(*args,**kwargs) # populates the form
self.fields['images'].queryset = KMSImageP.objects.all()
self.fields['categories'].queryset = Category.objects.all()
The through model
class EventCategorizing(Categorizing):
""" Intermediary model for Many2Many relationships between categories and Events."""
def __unicode__(self):
return "Show : InSearch:"+str(self.show_in_search_menu)\
+" InDesc:"+str(self.show_in_item_description)\
+" Child:"+str(self.show_child)+" cat:"+self.category.name
And its base
class Categorizing(models.Model):
""" Intermediary model for Many2Many relationships between categoris and events/locations."""
show_in_search_menu = models.BooleanField(default = True, )
show_in_item_description = models.BooleanField(default = False, )
show_child = models.BooleanField(default = True, )
category = models.ForeignKey(Category) #the category associated with the event/location
class Meta:
abstract = True
class Meta:
model = Event
exclude = ('slug',
'email',
'url_source',
'url_location',
'external_ref',
'creator',
'can_be_mapped',
)
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 ?