1

我有一个动态表单,并且由于参数“waysNumber”而导致 post 方法出错。问题出在 post 方法中的“formulari = WayForm(request.POST, request.FILES)”行中。它从 WayForm 执行函数 init(),现在没有名为waysNumber 的参数。传递此参数的正确方法是什么?这是我的代码:

表格.py:

class WayForm(forms.Form):

    def __init__(self, *args, **kwargs):         
        waysNumber = kwargs.pop("waysNumber")
        super(WayForm, self).__init__(*args, **kwargs)
        CHOICES = (('1','Pista',),('2','Corriol',))            
        for i in range(waysNumber):
            self.fields["Descripcio"+str(i)]= forms.CharField(widget=forms.Textarea(),label="Descripcio"+str(i))
            self.fields["Tipus"+str(i)] = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, label="Tipus de camí"+str(i))

视图.py:

def acoplar_track(request, track_id):    

    if request.method=='GET':
        track = get_object_or_404(Track, id=track_id) # obte el track i la zona corresponent al track   

        newWays_l = x.getTrackWays() # obte les ids dels nous camins que s'afegiran

        formulari = WayForm(waysNumber = len(newWays_l))                       
        return render(request,'principal/wayForm.html')

    else:
        formulari = WayForm(request.POST, request.FILES)
        if formulari.is_valid():   
            ...                       
            return render_to_response('principal/inici.html', context_instance=RequestContext(request))

谢谢你的帮助!

4

1 回答 1

0

问题是您没有跨请求保留值。一旦您发布帖子,您的参数就不会出现在WayForm实例上。为了解决这个问题,您可以像这样初始化表单:

def acoplar_track(request, track_id):
    newWays_l = x.getTrackWays()
    formulari = WayForm(request.POST or None, request.FILES or None,
        waysNumber = len(newWays_l))

    if request.method=='GET':
        track = get_object_or_404(Track, id=track_id)
        return render(request,'principal/wayForm.html')
    else:
        if formulari.is_valid():      
            return render_to_response('principal/inici.html',
                context_instance=RequestContext(request))
于 2013-06-20T01:33:53.323 回答