在Django中保存ManyToMany表格

时间:2014-03-04 14:12:29

标签: python django forms

如果用户提交表单,我试图将ManyToMany字段保存到我的数据库。当用户提交表单时,我可以看到数据库中的非M2M字段,但即使选择M2M字段,它们也不会显示。我一直在搜索很多东西并看到有关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 个答案:

答案 0 :(得分:0)

save_m2m是表单上的方法,而不是new_contact(模型的实例)。

但是如果您错过commit=False表单保存,则根本不需要调用它。使用save_m2m的唯一原因是当您使用commit=False时,如果要在正确保存之前设置任何实例字段,则需要执行此操作。如果您不想这样做,请直接执行form1.save(),然后无需拨打new_contact.save()save_m2m()