【问题标题】:Django Views: Is this the correct way to use the dispatch method of a Django class based view?Django Views:这是使用基于 Django 类的视图的调度方法的正确方法吗?
【发布时间】: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


【解决方案1】:

是的,正如您所做的那样覆盖 dispatch() 看起来没问题,并且避免了在 get()post() 中调用 obtainInformation 的重复。

在 Django 2.2+ 中,您可以使用一个新的 setup() 方法。

class View2(CustomView):

    def setup(self, request, *args, **kwargs):
        super().setup(request, *args, **kwargs)
        self.obtainInformation(kwargs)

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2018-08-21
    • 2015-10-08
    • 2016-05-20
    • 2015-12-02
    • 1970-01-01
    相关资源
    最近更新 更多