Django Forms:将参数传递给表单

时间:2013-02-02 08:22:11

标签: django django-forms

如何将参数传递给表单?

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

根据以下答案编辑:

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

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

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

3 个答案:

答案 0 :(得分:36)

您应该定义表单的__init__方法,如:

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

当然,在创建对象之前,您无法访问self.site_id,因此行:

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

毫无意义。您必须在创建表单后将该属性添加到窗口小部件。尝试这样的事情:

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()

(未经测试)

答案 1 :(得分:3)

这对我有用。我正在尝试制作自定义表格。模型中的此字段是charfield,但我想要动态生成的选择字段。

表格:

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', )

视图:

    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})

模板:

<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>

答案 2 :(得分:0)

someView()..
        form = StylesForm( 1, request.POST)

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()

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

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()