我正在尝试为之后需要进行子类化的应用程序构建FormView。遗憾的是,我无法通过子类设置formclass。
我的代码:
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'),
)
我做错了什么?
答案 0 :(得分:3)
请改为尝试:
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
答案 1 :(得分:2)
这不适用于TrainingCreateView
,因为__init__
视图执行以下操作
self.form_class = TrainingForm
super(TrainingCreateView, self).__init__(*args, **kwargs)
拨打__init__
的{{1}} ... EventCreateView
您可以通过更改self.formclass = EventForm
方法的顺序来解决此问题。请注意,该方法不必返回任何内容。
__init_
但是,从您编写的代码中,不清楚为什么需要在class TrainingCreateView(EventCreateView):
def __init__(self, *args, **kwargs):
super(TrainingCreateView, self).__init__(*args, **kwargs)
self.form_class = TrainingForm
方法中设置self.form_class
,而不是仅将其设置为类属性。如果您需要动态设置它,更好的选择可能是覆盖get_form_class
而不是。