0
我想保存一個ManyToMany字段到我的數據庫,如果用戶提交表單。當用戶提交表單時,我可以看到數據庫中的非M2M字段,但即使選擇M2M字段,他們也不會顯示。我一直在尋找很多東西,並且看到了有關m2m_save()函數的一些內容,但無法弄清楚。任何幫助是極大的讚賞! (我一直在尋找了很長時間,所以我希望我不是重複這個問題!)ManyToMay表格保存在Django
# 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'
非常感謝你已經爲你的幫助!
非常感謝你,工作很棒!你是一個很棒的人! – user3303769