使用动态 form_class 的 Updateview
我想在Django 1.6中动态改变一个UpdateView
类视图的form_class
。
我尝试过使用get_context_data()
来实现这个,但这没用,因为表单已经初始化了。所以我想这需要在__init__
方法中进行。
这是我在__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'属性
的错误信息。
当我手动指定id(比如id=9
)时,设置就能正常工作。
我该如何在我重写的init方法中获取args/kwargs呢?特别是我需要访问pk
。
1 个回答
9
你只需要重写一下 get_form_class
这个方法就可以了。
(另外,我不太明白你为什么要查询 person
:这个对象其实和 self.get_object()
是一样的,所以没必要再获取它的ID然后再去查询一次。)
def get_form_class(self):
if self.object.somefield:
return OneFormClass
else:
return SomeOtherFormClass