46

如何将参数传递给我的表单?

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
4

3 回答 3

60

您应该定义表单的 __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()

(未测试)

于 2013-02-02T08:24:45.010 回答
11

这对我有用。我试图制作一个自定义表单。模型中的这个字段是一个字符字段,但我想要一个动态生成的选择字段。

表格:

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>
于 2018-10-03T06:40:43.417 回答
4
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()
于 2020-09-17T19:50:45.543 回答