django形成传递参数

时间:2013-06-19 23:52:31

标签: django django-forms django-views

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

forms.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))

views.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))

感谢您的帮助!

1 个答案:

答案 0 :(得分: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))