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

时间:2022-01-18 23:19:38

I have a Dynamic Form in forms. How can I pass an argument from my view when I instantiate my form?

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

Something like:

就像是:

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

This is the form I have:

这是我的形式:

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)

1 个解决方案

#1


46  

Add it as keyword argument, say it's called my_arg. Make sure to pop() the keyword arg before calling super(), because the parent class's init method doesn't accept extra keyword arguments.

将它添加为关键字参数,比如称为my_arg。确保在调用super()之前pop()关键字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)

And when you create form it's like this:

当你创建表单时,它是这样的:

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

#1


46  

Add it as keyword argument, say it's called my_arg. Make sure to pop() the keyword arg before calling super(), because the parent class's init method doesn't accept extra keyword arguments.

将它添加为关键字参数,比如称为my_arg。确保在调用super()之前pop()关键字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)

And when you create form it's like this:

当你创建表单时,它是这样的:

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