如何从视图将值传递给 Django Form init 方法?
Posted
技术标签:
【中文标题】如何从视图将值传递给 Django Form init 方法?【英文标题】:How can I pass a value to Django Form's init method from a view? 【发布时间】:2015-03-28 01:42:35 【问题描述】:forms.py
class AddDuration(forms.Form):
def __init__(self, *args, **kwargs):
super(AddDuration, self).__init__(*args, **kwargs)
// set value to relates_to_choices
relates_to_choices = ????????????? // Something like self.choices
self.fields['duration'].choices = relates_to_choices
duration = forms.ChoiceField(required=True)
现在,我有一个包含类的 views.py 文件
class AddDurationView(FormView):
template_name = 'physician/add_duration.html'
form_class = AddDurationForm
【问题讨论】:
【参考方案1】:覆盖视图上的get_form_kwargs()
方法。
views.py
class AddDurationView(FormView):
template_name = 'physician/add_duration.html'
form_class = AddDurationForm
def get_form_kwargs(self):
kwargs = super(AddDurationView, self).get_form_kwargs()
kwargs['duration_choices'] = (
('key1', 'display value 1'),
('key2', 'display value 2'),
)
return kwargs
forms.py
class AddDurationForm(forms.Form):
duration = forms.ChoiceField(required=True)
def __init__(self, duration_choices, *args, **kwargs):
super(AddDurationForm, self).__init__(*args, **kwargs)
// set value to duration_choices
self.fields['duration'].choices = duration_choices
【讨论】:
以上是关于如何从视图将值传递给 Django Form init 方法?的主要内容,如果未能解决你的问题,请参考以下文章
通过jQuery ajax调用将值列表传递给django视图
如何将值从 javascript 函数传递到 django 视图