Django Forms: pass parameter to form

后端 未结 3 1465
悲哀的现实
悲哀的现实 2020-12-01 06:02

How do I pass a parameter to my form?

someView()..
    form = StylesForm(data_dict) # I also want to pass in site_id here.

class StylesForm(forms.Form):
             


        
3条回答
  •  佛祖请我去吃肉
    2020-12-01 06:50

    You should define the __init__ method of your form, like that:

    class StylesForm(forms.Form):
        def __init__(self,*args,**kwargs):
            self.site_id = kwargs.pop('site_id')
            super(StylesForm,self).__init__(*args,**kwargs)
    

    of course you cannot access self.site_id until the object has been created, so the line:

         height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))
    

    makes no sense. You have to add the attribute to the widget after the form has been created. Try something like this:

    class StylesForm(forms.Form):
        def __init__(self,*args,**kwargs):
            self.site_id = kwargs.pop('site_id')
            super(StylesForm,self).__init__(*args,**kwargs)
            self.fields['height'].widget = forms.TextInput(attrs={'size':site_id})
    
        height = forms.CharField()
    

    (not tested)

提交回复
热议问题