Django:从CBV表单视图传递数据以形成CBV [英] Django: pass data from CBV form view to form CBV
问题描述
我有表单
与 ModelChoiceField
,它被用作 form_class
在 FormView
中。
I have Form
with a ModelChoiceField
, which is being used as the form_class
in a FormView
.
选择字段必须填充绑定到请求
对象。
The choice field has to be populated with information bound to the request
object.
总结一下:
class MyFormView(FormView):
# I need to pass `request.user` and a value
# derived from `request.GET['pk']` to the form
form_class = MyForm
class MyForm(Form):
choices = ModelChoiceField(queryset=MyChoice.objects.none())
def __init__(self, user, number, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['choices'] = MyChoice.objects(number=number, owner=user)
我需要做什么才能将数据传递给创建实例时的形式?
What would I need to do to pass that data to the form when its instance is created?
我尝试覆盖 get_form
但我不确定他是正确的方法:
I tried overriding get_form
but I am unsure this is the proper way of doing this:
def get_form(self, form_class):
user = self.request.user
number = SomeModel.objects.get(self.GET['pk']).number
return form_class(user, number, **self.get_form_kwargs())
推荐答案
覆盖 get_form
,但更好的方法是覆盖 get_form_kwargs
,以便您不必从 get_form
方法
Overriding get_form
would work, but a better approach would be to override get_form_kwargs
, so that you don't have to duplicate code from the get_form
method.
class MyFormView(FormView):
form_class = MyForm
def get_form_kwargs(self):
kwargs = super(MyFormView, self).get_form_kwargs()
kwargs['user'] = self.request.user
kwargs['number'] = SomeModel.objects.get(self.GET['pk']).number
return kwargs
这篇关于Django:从CBV表单视图传递数据以形成CBV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!