我开始使用django(和stackoverflow!)
我一直在尝试创建一个包含表单和项目列表的网页。 (Django - Mixing ListView and CreateView)。我提出了一个解决方案,但我不相信我的代码!
我正在使用Django mixin BaseCreateView
和BaseListView
来生成表单和列表上下文数据。但由于它的观点,他们直接调用render_to_response()
。
所以我重载了get()
方法来手动调用两个父方法并提取上下文数据。然后我自己打电话给render_to_response()
。
class FormAndListView(BaseCreateView, BaseListView, TemplateResponseMixin):
def get(self, request, *args, **kwargs):
formView = BaseCreateView.get(self, request, *args, **kwargs) # formView contains a response_class
listView = BaseListView.get(self, request, *args, **kwargs) # listView contains a response_class as well...
formData = formView.context_data['form'] # extract the form from the response_class
listData = listView.context_data['object_list'] # extract the object list from the response_class
return render_to_response('textfrompdf/index.html', {'form' : formData, 'all_PDF' : listData},
context_instance=RequestContext(request))
一方面,我不会重新编写mixin中的内容来管理表单和项目列表......另一方面,django正在计算整个render_to_response()
3次!
编写此页面的干净Django方法是什么?
答案 0 :(得分:1)
class FormAndListView(BaseCreateView, BaseListView, TemplateResponseMixin):
def render_to_response(context, **responsekwargs)
return context
def get(self, request, *args, **kwargs):
context = {}
context.update( BaseCreateView.get(self, request, *args, **kwargs) ) # formView contains a response_class
context.update( BaseListView.get(self, request, *args, **kwargs) ) # listView contains a response_class as well...
return TemplateResponseMixin.render_to_response('textfrompdf/index.html', context,
context_instance=RequestContext(request))