這是我forms.pyDjango的多選,如何覆蓋選擇正確
CHOICES = []
class salDeptChartForm(forms.Form):
company = forms.CharField(max_length=2,label = 'Firma',help_text='A valid email address, please.')
date_validfrom = forms.DateField(label = 'Bu Tarihten',required=False)
date_validuntil = forms.DateField(label = 'Bu Tarihe Kadar',required=False)
saldept = forms.MultipleChoiceField(label = 'Satış Departmanları',choices=CHOICES, widget=forms.CheckboxSelectMultiple())
這是我重寫我的觀點的選擇。
form = salDeptChartForm(initial={'company':'01'})
saldeptlist = saleinstance.fetchSalDept()
form.fields['saldept'].choices = saldeptlist <this is where I override>
當我選擇其中一個選項時會發生問題。表單不會得到驗證。
Select a valid choice. * is not one of the available choices.
我想,即使我重寫我的觀點的Django的選擇仍與以前的選擇檢查itially我創建的。我得到了正確的html輸出。
如何克服這一點? thx
完整的視圖代碼在那裏。 形式發起兩次獲得和一次發佈,我不知道它是否最好。因爲你只覆蓋在GET
方法的選擇
def salDept(request):
member_id = request.session['member_id']
saleinstance = sale(member_id)
chartinstance = charts(member_id)
if request.method == 'GET':
form = salDeptChartForm(initial={'company':'01'}) <first init>
saldeptlist = saleinstance.fetchSalDept() <its a list>
form.fields['saldept'].choices = saldeptlist <override choices>
print 'get worked'
return render(request, 'chart/sale/salDept.html',locals())
if request.method == 'POST':
form = salDeptChartForm(request.POST) <second init>
print 'post worked'
if form.is_valid(): <fails>
print 'valid'
company = form.cleaned_data['company']
vfr = form.cleaned_data['date_validfrom']
vun = form.cleaned_data['date_validuntil']
validfrom = formatDate(vfr)
validuntil = formatDate(vun)
selectedSalDepts = request.POST.getlist('saldept')
else:
print 'not valid'
print form.errors
resultdict = chartinstance.salesBySaldept(company,selectedSalDepts,validfrom, validuntil)
form = salDeptChartForm(initial={'company':company,'date_validfrom':request.POST['date_validfrom'], 'date_validuntil':request.POST['date_validuntil']})
domcache = 'true'
return render(request, 'chart/sale/salDept.html',locals())
我不喜歡重複的代碼的選擇,那麼有沒有辦法只有一種形式開始和一個選擇覆蓋來實現這一目標? – durdenk
是的。它可能需要你創建一些幫助函數,或者你可能會考慮查看基於類的視圖。在這樣的情況下,他們會很完美。這是很好的介紹對他們說:http://www.youtube.com/watch?v=yr9HOLipPXc – miki725