python 将参数传递给 Django 中的动态表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2237064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing arguments to a dynamic form in django
提问by user140736
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)
回答by gruszczy
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。pop()
在调用之前确保关键字 arg super()
,因为父类的 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')
回答by unlockme
You can also achieve this by overriding the get_form_kwargs
of the FormMixin, available in class based views.
您还可以通过覆盖get_form_kwargs
基于类的视图中可用的 FormMixin 的来实现这一点。
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
Then in your form
然后在你的表格中
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