具有动态form_class的Updateview [英] Updateview with dynamic form_class
问题描述
我想在Django 1.6中动态更改 UpdateView
CBV的 form_class
.
I would like to dynamically change the form_class
of an UpdateView
CBV in Django 1.6.
我尝试使用get_context_data()进行此操作,但这没有帮助,因为表单已经初始化.我想这将需要在 __ init __
期间发生.这是我在 __ init __
上尝试过的方法:
I've tried to do this using the get_context_data(), but that didn't help since the form is already initialized. So it will need to happen during __init__
, I guess.
Here's what I've tried on __init__
:
class UpdatePersonView(generic.UpdateView):
model = Person
form_class = ""
def __init__(self, *args, **kwargs):
super(UpdatePersonView, self).__init__(*args, **kwargs)
person = Person.objects.get(id=self.get_object().id)
if not person.somefield:
self.form_class = OneFormClass
elif person.somefield:
self.form_class = SomeOtherFormClass
当执行 person = Person.objects.get(id = self.get_object().id)时,我陷入了
.'UpdatePersonView'对象没有属性'kwargs'
错误消息的问题)
I'm stuck with a 'UpdatePersonView' object has no attribute 'kwargs'
error message when executing person = Person.objects.get(id=self.get_object().id)
.
手动指定ID(例如 id = 9
)时,设置即可正常工作.
When manually specifying the id (e.g. id=9
), then the setup works.
如何在要覆盖的 init 方法中获取args/kwargs?特别是我需要访问 pk
.
How can I get the args/kwargs inside the init method that I'm overriding? Particularly I would need access to the pk
.
推荐答案
You should simply override get_form_class
.
(而且我不确定为什么要查询 person
:那个对象已经是 self.get_object()
了,所以毫无意义的ID,然后再次查询.)
(Also I'm not sure why you're querying for person
: that object is the same is self.get_object()
already, so there's no point getting the ID of that then querying again.)
def get_form_class(self):
if self.object.somefield:
return OneFormClass
else:
return SomeOtherFormClass
这篇关于具有动态form_class的Updateview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!