我對Django相當新(實際上是4個月),在過去的2天裏我一直在爲這個問題苦苦掙扎,我想我犯了一些愚蠢的錯誤。任何幫助或輸入是高度讚賞。我正在使用Django 1.3。CheckboxSelectMultiple和ManyToManyField帶有Modelform的問題
在模型中我有,
BUSINESS_GROUP = (
('MNC','Multinational'),
('INT','International (Export/Import)'),
('DOM','Domestic/National'),
('LOC','Local'),
('VIR','Virtual'),
)
class BusinessGroup(models.Model):
bgroup_type = models.CharField(max_length=15, choices = BUSINESS_GROUP, blank = True, null = True)
class Business(models.Model):
business_group_choices = models.ManyToManyField(BusinessGroup, verbose_name= "Business Group")
在形式上我有這樣的事情,
def __init__(self, *args, **kwargs):
super(BusinessForm, self).__init__(*args, **kwargs)
self.fields['business_group_choices'].widget = forms.CheckboxSelectMultiple(choices=BUSINESS_GROUP)
在視圖中,
if request.method == 'POST':
form = BusinessForm(request.POST, instance = business)
if form.is_valid():
new_business = form.save(commit=False)
new_business.created_by = request.user
form_values = form.cleaned_data
new_business.save()
assign('edit_business', request.user, new_business)
return HttpResponseRedirect(new_business.get_absolute_url())
我得到這樣的錯誤,
"DOM" is not a valid value for a primary key.
"INT" is not a valid value for a primary key.
等
我發現source of error here in Django model source,
但尚不清楚如何解釋和鍛鍊了這個問題。
編輯: 我試圖使場空=真和/或空白=真還是我得到驗證錯誤,爲什麼呢?
隨着整個安裝我得到這個新的錯誤一些變化,
Select a valid choice. [u'MNC', u'INT', u'DOM', u'LOC', u'VIR'] is not one of the available choices.
新設置: 在模型
class BusinessGroup(models.Model):
bgroup_type = models.CharField(max_length=15)
class Business(models.Model):
business_group_choices = models.ManyToManyField(BusinessGroup, verbose_name= "Business Group", choices=BUSINESS_GROUP)
在形式上我有這樣的事情,
def __init__(self, *args, **kwargs):
super(BusinessForm, self).__init__(*args, **kwargs)
self.fields['business_group_choices'].widget = forms.CheckboxSelectMultiple(choices=BUSINESS_GROUP)
感謝布蘭登,我真的很感激輸入。 –
不客氣。 – Brandon
我認爲你的解決方案非常好,我在2天后意識到,最終混合了你的一些想法。很好的學習,但再次感謝 –