重写Django的get_form_class()方法会引发字符串错误

时间:2016-05-29 14:43:27

标签: python django django-class-based-views

我有一个基于类的视图,它应该根据动物的名称动态选择一个表单。

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作为正确的数据类型而不是字符串返回?

1 个答案:

答案 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, # <-
}