-1

出于某种原因,我无法像过去那样填充表单的字段。以下是相关位:

视图.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})

表格.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变量都是空字典?为什么会这样?

4

1 回答 1

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
于 2013-07-05T19:28:43.567 回答