Django Forms: pass parameter to form

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)

Leave a Comment