django:子类 FormView 两次并覆盖 form_class

django: subclass FormView twice and override form_class

我正在尝试为之后需要子类化的应用构建 FormView。遗憾的是我无法通过子类设置表单类。

我的代码:

class EventCreateView(FormView):
    template_name='Events/add_event_form.html'
    success_url = reverse_lazy('events_list')
    form_class = None  # replaced by __init__ function

    def __init__(self, *args, **kwargs):
        self.form_class=EventForm
        return super(EventCreateView, self).__init__(*args, **kwargs)

    #other functions, not shown here .. 


class TrainingCreateView(EventCreateView):
    def __init__(self, *args, **kwargs):
        self.form_class=TrainingForm
        return super(TrainingCreateView, self).__init__(*args, **kwargs)

urls.py:

 urlpatterns = patterns('',
     url(r'event/event/add/$', EventCreateView.as_view(), name='event_add'),
     url(r'event/training/add/$', TrainingCreateView.as_view(), name='training_add'),
 )

我做错了什么?

这对 TrainingCreateView 不起作用,因为 __init__ 视图执行以下操作

  1. 设置self.form_class = TrainingForm
  2. super(TrainingCreateView, self).__init__(*args, **kwargs) 调用 EventCreateView__init__ ...
  3. 设置self.formclass = EventForm

您可以通过更改 __init_ 方法的顺序来解决这个问题。请注意,该方法不必 return 任何内容。

class TrainingCreateView(EventCreateView):
    def __init__(self, *args, **kwargs):
        super(TrainingCreateView, self).__init__(*args, **kwargs)
        self.form_class = TrainingForm

但是,从您编写的代码来看,不清楚为什么需要在 __init__ 方法中设置 self.form_class,而不是将其设置为 class属性。如果您需要动态设置它,更好的选择可能是覆盖 get_form_class

试试这个:

class EventCreateView(FormView):
    template_name='Events/add_event_form.html'
    success_url = reverse_lazy('events_list')
    form_class = EventForm

    ...

class TrainingCreateView(EventCreateView):
    form_class = TrainingForm