Django Multiselect,如何正确覆盖选择

时间:2012-11-12 01:53:50

标签: django forms override

这是我的forms.py

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仍会检查我之前创建的先前选择。我得到了正确的html输出。

如何克服这个? THX

完整的视图代码就在那里。 表单启动两次一次获取,一次发布,我不知道它是否也是最好的。

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())

2 个答案:

答案 0 :(得分:2)

好的,您需要覆盖表单的 init ()来完成此操作。

class SomeForm(forms.Form):
    email       = forms.EmailField(label=(u'Email Address'))
    users       = forms.MultipleChoiceField(choices=[(x, x) for x in User.objects.all()]
)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(SomeForm, self).__init__(*args, **kwargs)
            self.fields['users'].choices = [(x, x) for x in User.objects.filter(name__contains='Patel')]


    def clean(self):
        return self.cleaned_datas

在行号(3)中,您可以看到我提供了所有可能的选择,然后在 init 中我已经过滤了选项,这很重要,因为Django会验证您提交的请求。前者并显示后者的选择

答案 1 :(得分:0)

您的验证失败,因为您只覆盖GET方法上的选项。你没有为POST做任何事情,所以就Django而言,没有选择对POST有效。将选项添加到POST可以解决您的问题。