0

这是我的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 输出。

如何克服这一点?谢谢

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

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

2 回答 2

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 验证您从前者提交的请求并显示来自后者的选择

于 2012-11-29T13:57:50.950 回答
0

您的验证失败,因为您只覆盖了GET方法上的选择。你不POSTPOST. 添加选项POST应该可以解决您的问题。

于 2012-11-12T02:01:40.053 回答