53

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):
    # I want access to site_id here
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
user984003
  • 28,050
  • 64
  • 189
  • 285

3 Answers3

68

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)

Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64
  • How do I access site_id in the form? I've tried self.site_id and site_id. That gives me an error. I used breakpoints, and it seems that it passes through all my field definitions (where I need to use site_id) before it passes though the _init_ – user984003 Feb 02 '13 at 08:50
  • 2
    Use self.site_id to access the field. The __init__ method is called before any other method, double check it. – Emanuele Paolini Feb 02 '13 at 08:54
  • I get "name 'self' is not defined" – user984003 Feb 02 '13 at 08:55
  • Not sure if this is clear from my comment above, but it's still not working. – user984003 Feb 02 '13 at 10:28
  • Hmm. I have about 30 form fields that use this variable. Would hate to add 30 extra lines of code, one for each field. Will see what I can do, I guess. – user984003 Feb 02 '13 at 21:29
12

This is what worked for me. I was trying to make a custom form . This field in the model is a charfield but I wanted a choice field generated dynamically .

The Form:

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

The Views:

    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

The Template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
     {{ interview }}
    {% if rounds %}
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}
</form>
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63
6
someView()..
        form = StylesForm( 1, request.POST)

in forms.py

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

     height = forms.CharField()

or

someView()..
            form = StylesForm(site_id = 1)

in forms.py

class StylesForm(forms.Form):
         #overwrite __init__
         def __init__(self,site_id):
              # call standard __init__
              super().__init__()
              #extend __init__
              self.fields['height'] =forms.CharField(widget=forms.TextInput(       
                                                         attrs= {'size':site_id}))
    
         height = forms.CharField()
Sven M
  • 61
  • 1
  • 2