有一个基于功能的视图,如下所示:
def class_based_foo(request, id):
domain = get_object_or_404(Domain, id=id)
..
# here comes 20 lines of code for domain
..
if request.method == 'POST':
# do smth that requires domain
else:
# do smth else that also requires domain but doesn't relate to POST
return render(request, 'foo.html', {'domain': domain}
问题是:如何将此转换为基于类的视图?
这个想法是:
class FooView(TemplateView):
template_name = 'foo.html'
def render_to_response(self, context, **kwargs):
return render(self.request, self.get_template_names()[0], context)
def get_context_data(self, domain_id, **kwargs):
context = super(EditDomainView, self).get_context_data(**kwargs)
..
# lots of domain-related stuff
..
# do smth else that also requires domain but doesn't relate to POST
return context
def post(self, request, *args, **kwargs):
# do smth that requires domain
# but where to get domain from? Copy-paste 20 lines of code again?
答案 0 :(得分:1)
不要将此功能转换为基于类的视图。你的功能干净,易懂。基于类的视图将是一堆乱七八糟的代码。
如果你真的需要使用CBV,那么继承UpdateView。您可以将域值保存为self
的属性,然后以各种方法访问它们:
self.some_data = "some data"
thread safe操作。