django表单构造函数不返回字段?

时间:2013-07-05 19:13:40

标签: django forms django-forms

由于某些原因,我无法像过去那样填充表单的字段。这是相关的部分:

views.py

def selectEvent(request, user=None):
    if not user:
        userID = request.user.id

    if request.method == 'POST':
        qform = eventForm(request.POST, user=userID)
        if qform.is_valid():
            qryData = qform.cleaned_data
            event = qryData['event']
            qurl = '/showGG/getWedGuest/%s' % (event)
            return HttpResponseRedirect(qurl)
    else:
        qform = eventForm(user=userID)

    return render(request, 'showGG/getEvent.html', {'form': qform})

forms.py

class eventForm(forms.Form):

    def __init__(self, *args, **kwargs):
        user=kwargs.pop('user')
        super(eventForm, self).__init__(*args, **kwargs)
        elist = [(e,e.name) for e in Event.objects.filter(organizer_id__exact=user)]
        print 'eventForm: elist=',elist
        event = forms.ChoiceField(choices=elist)

我需要复杂的eventForm.__init__()因为我传给它一个变量,但打印线 表明它正在产生我期望的列表:

eventForm: elist= [(<Event: cd2 - 2013-08-01 00:17:39+00:00>, u'cd2')]

但是当我将qform返回到views.selectEvent时,其fieldsbase_fields变量都是空字典?为什么会这样?

1 个答案:

答案 0 :(得分:1)

因为您尚未在表单上定义任何字段。你不能只在__init__中设置它们并希望它能够正常工作:正在进行复杂的元类,并且定义必须在类级别。您在__init__中可以执行的操作将覆盖现有字段的选项:

class eventForm(forms.Form):
    event = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        user=kwargs.pop('user')
        super(eventForm, self).__init__(*args, **kwargs)
        elist = [(e.id,e.name) for e in Event.objects.filter(organizer_id__exact=user)]
        self.fields['event'].choices = elist