从功能转换为基于类的视图

时间:2015-01-22 13:51:33

标签: python django

有一个基于功能的视图,如下所示:

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}

问题是:如何将此转换为基于类的视图?

  • 使用什么通用Django视图作为基础?
  • 如何将其分成几部分,这样就不需要复制粘贴20行与域相关的代码了?

这个想法是:

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?

1 个答案:

答案 0 :(得分:1)

不要将此功能转换为基于类的视图。你的功能干净,易懂。基于类的视图将是一堆乱七八糟的代码。

如果你真的需要使用CBV,那么继承UpdateView。您可以将域值保存为self的属性,然后以各种方法访问它们:

self.some_data = "some data"

thread safe操作。