将参数传递给django中的动态表单

时间:2010-02-10 13:28:07

标签: python django django-forms

我在表单中有一个动态表单。当我实例化表单时,如何从我的视图中传递参数?

类似的东西:

form = DynamicForm("some string argument I'm passing to my form")

这是我的形式:

class DynamicForm(Form):
def __init__(self, *args, **kwargs):
    super(DynamicForm, self).__init__(*args, **kwargs)
    for item in range(5):
        self.fields['test_field_%d' % item] = CharField(max_length=255)

2 个答案:

答案 0 :(得分:46)

将其添加为关键字参数,假设它名为my_arg。在调用pop()之前,请确保super()关键字arg,因为父类的init方法不接受额外的关键字参数。

class DynamicForm(Form):
  def __init__(self, *args, **kwargs):
    my_arg = kwargs.pop('my_arg')
    super(DynamicForm, self).__init__(*args, **kwargs)
    for item in range(5):
        self.fields['test_field_%d' % item] = CharField(max_length=255)

当你创建表单时,就像这样:

form = DynamicForm(..., my_arg='value')

答案 1 :(得分:0)

您还可以通过重写FormMixin的get_form_kwargs(在基于类的视图中提供)来实现此目的。

class CustomDynamicFormView(FormView):  # inherit any view with formmixin...
      form_class = DynamicForm

      def get_form_kwargs(self):
          kwargs = super(CustomDynamicFormView, self).get_form_kwargs()
          kwargs['custom_variable'] = 'my custom variable'
          return kwargs

然后以您的形式

class DynamicForm(forms.Form):
    def __init__(self, *args, *kwargs):
        my_var = kwargs.pop('custom_variable') 
        # remove this b4 calling super otherwise it will complian
        super(DynamicForm, self).__init__(*args, **kwargs)
        # do what you want with my_var

For more information check here