Django中ManyToMany表单保存
我正在尝试将一个多对多(ManyToMany)字段保存到我的数据库中,当用户提交表单时。我发现用户提交表单后,非多对多字段的数据能正常显示在数据库里,但即使选择了多对多字段,它们也不会显示出来。我搜索了很多资料,看到一些关于m2m_save()函数的内容,但还是搞不明白。非常感谢任何帮助!(我已经搜索了很久,希望我没有重复这个问题!)
# 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))
当我运行这个时,我收到了这个:
AttributeError at /app/
'Contact' object has no attribute 'save_m2m'
1 个回答
1
save_m2m
是一个在表单上的方法,而不是在 new_contact
上(后者是模型的一个实例)。
不过,如果你在保存表单时没有使用 commit=False
,其实根本不需要调用这个方法。使用 save_m2m
的唯一原因是当你使用 commit=False
时,这样做是为了在正式保存之前设置一些实例字段。如果你不想这样做,就像这里一样,直接使用 form1.save()
就可以了,这样就不需要再调用 new_contact.save()
或 save_m2m()
了。