我有一个基于类的视图,它应该根据动物的名称动态选择一个表单。
UpdateAnimalView(FormMixin, DetailView):
def get_form_class(self):
SOME_FORMS = {
"Dog" : "UpdateDogForm",
"Cat" : "UpdateCatForm",
"Frog" : "UpdateFrogForm",
}
animal = object
animal_type = object.type #returns "Dog", "Cat" or "Frog"
form_class_name = SOME_FORMS[animal_type]
#form_class_name now takes the values "UpdateDogForm"
#, "UpdateCatForm" or "UpdateFrogFrom"
return form_class_name
但是,当我运行它时,它似乎不会读取form_class
而是作为string
而Django会抛出此错误:
'str' object is not callable
追溯来自get_context_data
。我推断出callstack如下:
def get_form(self, form_class=None):
form = super(UpdateAnimalView, self).get_form()
return form
def get_context_data(self, **kwargs):
context = super(UpdateAnimalView, self).get_context_data(**kwargs)
context['form'] = self.get_form()
return context
如何将form_class
作为正确的数据类型而不是字符串返回?
答案 0 :(得分:3)
get_form_class
应返回实际的类,而不是其名称:
# import the form classes from wherever they live
from .forms import UpdateDogForm, UpdateCatForm, UpdateFrogForm
...
SOME_FORMS = {
"Dog": UpdateDogForm, # <- no string values here!
"Cat": UpdateCatForm, # <-
"Frog": UpdateFrogForm, # <-
}