我有一个基于类的视图,该视图应该根据动物的名称动态选择一种形式。

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。我推断出调用栈如下:

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

最佳答案

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

关于python - 重写Django的get_form_class()方法会引发字符串错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37511232/

10-12 13:03
查看更多