Django表单:将参数传递给表单

Django表单:将参数传递给表单,django,django-forms,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 您应该定义表单的_init__方法,如下所示: class StylesForm(forms.Form): def __init__(self,*args,**kw

如何将参数传递到窗体

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

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

(未经测试)

这对我来说很有效。我在试着做一个自定义表单。模型中的这个字段是charfield,但我希望动态生成一个choice字段

表格:

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>
视图:

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>
模板:

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>

{%csrf_令牌%}
{%if采访%}
{{采访}
{%if rounds%}
{{form.as_p}}
{%else%}
没有找到子弹
{%endif%}
在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()
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()

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

如何访问表单中的站点id?我尝试了self.site\u id和site\u id。这给了我一个错误。我使用了断点,它似乎在通过initUse self.site_id访问字段之前,先通过了我所有的字段定义(我需要使用site_id)。在调用任何其他方法之前先调用init方法,请仔细检查它。我得到“name'self'未定义”不确定我上面的评论是否清楚,但它仍然不起作用。嗯。我有大约30个表单字段使用这个变量。不愿意再增加30行代码,每个字段一行。我想我会看看我能做些什么。为什么我不能用这个简单的逻辑。。。非常感谢你。