Reputation: 75
I am trying to save a ManyToMany field to my database if the user submits the form. When the user submits the form, I can see the non-M2M fields in the database, but even when selecting the M2M fields they will not show up. I have been searching around a lot and seen some things about the m2m_save() function but couldn't figure it out. Any help is greatly appreciated! (I have been searching for a long time, so I hope I am not repeating this question!)
# models.py
class Contact(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
contactinfo = models.ForeignKey(ContactInfo)
location = models.ForeignKey(Location, null=True, blank=True)
work = models.ManyToManyField(Work, null=True, blank=True)
skills = models.ManyToManyField(Skills, null=True, blank=True)
contactgroup = models.ManyToManyField(ContactGroup, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Meta:
ordering = ["first_name",]
#forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
#exclude = ('work', 'skills', 'contactgroup')
first_name = forms.TextInput(),
last_name = forms.TextInput(),
contactinfo = forms.ModelChoiceField(queryset=ContactInfo.objects.all()),
location = forms.ModelChoiceField(queryset=Location.objects.all()),
work = forms.ModelMultipleChoiceField(queryset=Work.objects.all()),
skills = forms.ModelMultipleChoiceField(queryset=Skills.objects.all()),
contactgroup = forms.ModelMultipleChoiceField(queryset=ContactGroup.objects.all()),
widgets = {
'first_name': forms.TextInput(attrs={'placeholder': 'First'}),
'last_name': forms.TextInput(attrs={'placeholder': 'Last'}),
}
# views.py
def apphome(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/')
form1 = ContactForm(request.POST or None)
if form1.is_valid():
new_contact = form1.save(commit=False)
new_contact.save()
new_contact.save_m2m()
return HttpResponseRedirect("/app")
return render_to_response("apphome.html", locals(), context_instance=RequestContext(request))
When I run this, I receive this:
AttributeError at /app/
'Contact' object has no attribute 'save_m2m'
Upvotes: 1
Views: 678
Reputation: 599490
save_m2m
is a method on the form, not on new_contact
(which is an instance of the model).
But you don't need to call it at all if you miss out the commit=False
to the form save. The only reason for having save_m2m
is for when you do use commit=False
, which you would want to do if you want to set any instance fields before saving properly. If you don't want to do that, as here, just do form1.save()
directly, then there's no need to call either new_contact.save()
or save_m2m()
.
Upvotes: 1