【发布时间】:2019-05-29 23:14:46
【问题描述】:
我有一个基于类的视图,并且从 get 和 post 请求中我一直在调用一个方法,以从 HttpResponseRedirect kwargs 中的信息中获取信息。
代码:
class View1(View):
def get(self, request, *args, **kwargs):
... stuff ...
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
... stuff ...
return HttpResponseRedirect(
reverse('results:report_experiment',
kwargs={
'sample_id': current_sample_id
}
))
class View2(CustomView):
def obtainInformation(self, kwargs):
sample_id = kwargs.get('sample_id', None)
self.sample_obj = Sample.objects.get(id=sample_id)
def dispatch(self, request, *args, **kwargs):
self.obtainInformation(kwargs)
return super(View2, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
... stuff ...
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
... stuff ...
return HttpResponseRedirect(
reverse('results:report_experiment',
kwargs={
'sample_id': current_sample_id
}
))
我的问题是,当我在 dispatch 方法中调用 self.obtainInformation(kwargs) 时,我可以访问我在 get 和 post 方法中定义的任何类变量。以前我在 view2 的 get 和 post 方法中都调用了 self.obtainInformation(kwargs) (所以调用了两次该方法)。
这是使用 dispatch 方法的明智方式吗?
【问题讨论】:
-
你能告诉我们你的获取信息功能吗?不知道你想做什么
-
另外:您永远不应该在 CBV 中返回渲染,如果您需要在 get 中执行 stuf,只需返回
super(ViewName, self).get(request, *args, **kwargs) -
您好,obtainInformation方法是获取样本信息。即我使用 sample_id 来获取模型对象。这是一个非常简化的例子,我实际上得到了更多的信息。我只是在想,与其调用这个获取信息方法两次(在 GET 和 POST 中),我可以调用一次(在 DISPATCH 中),然后能够在 GET 和 POST 中访问 self 变量
-
我现在意识到,无论如何我都会调用该方法两次——没关系!而且我不明白 - 为什么我不应该在 CBV 中返回渲染?
-
抱歉,基本视图实际上并非如此。所有其他 CBV 将为您呈现模板,因此无需为它们调用 render。你做对了
标签: django django-views