在django重用类似的观点

时间:2017-11-08 15:44:58

标签: django django-views

class SupervisionView(MyBaseView, TemplateView):
    template_name = 'research/a1.html'

    def get_context_data(self, **kwargs):
        context = super(SupervisionView, self).get_context_data(**kwargs)
        context['supervisions'] = list1
        return context

    def post(self, request, *args, **kwargs):
        if 'confirm_supervision1' in request.POST:
            return redirect(reverse_lazy('t_app:dept1', kwargs={'year': self.kwargs['year']}))


class SupervisionView2(MyBaseView, TemplateView):
    template_name = 'research/a2.html'

    def get_context_data(self, **kwargs):
        context = super(SupervisionView2, self).get_context_data(**kwargs)
        context['supervisions'] = list 2
        return context

    def post(self, request, *args, **kwargs):
        if 'confirm_supervision2' in request.POST:
            return redirect(reverse_lazy('t_app:dept2', kwargs={'year': self.kwargs['year']}))

我有20多个函数再次做同样的事情。只有更改是每个视图中的上下文变量和重定向URL。压缩这个的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

你可以自定义mixin:

class MyDRYMixin(object):
    context_variable = None
    post_variable = None
    redirect_name = None

    def get_context_data(self, **kwargs):
        context = super(MyDRYMixin, self).get_context_data(**kwargs)
        if self.context_variable is not None:
            context['supervisions'] = self.context_variable
        return context

    def post(self, request, *args, **kwargs):
        if self.post_variable is not None and self.post_variable in request.POST:
            return redirect(reverse_lazy(self.redirect_name, kwargs={'year':self.kwargs['year']}

然后在视图中使用mixin,确保定义这三个变量:

class SupervisionView(MyBaseView, MyDRYMixin, TemplateView):
    template_name = 'research/a1.html'
    context_variable = 'list1'
    post_variable = 'confirm_supervision1'
    redirect_name = 't_app:dept1'

您可以将变量设置为您想要的任何值。将MyDRYMixin混合到视图中时,将使用您在该视图中提供的值,而不是基础mixin类中定义的值。因此,在上面的示例中,context_variable == list1。如果我们未在context_variable中定义SupervisionView,则默认为None,我们的基础mixin中设置的值。

如果您希望context_variable引用当前用户,例如:

class SupervisionView(MyBaseView, MyDRYMixin, TemplateView):
    context_variable = self.request.user
    ...

(编辑:我在这里犯了错误!这应该在get_context_data内完成,因为我们正在访问self.request.userhttps://docs.djangoproject.com/en/1.11/ref/class-based-views/mixins-simple/

或者您可能想要应用某种测试,例如对经过身份验证的用户使用一个context_variable,为未经身份验证的用户使用另一个;

class SupervisionView(MyBaseView, MyDRYMixin, TemplateView):
    def set_context_variable(self):
        if self.request.user.is_authenticated():
            self.context_variable = 'foo'
        else:
            self.context_variable = 'bar'

或者:

class SupervisionView(MyBaseView, MyDRYMixin, TemplateView):
    def get_context_variable(self):
        if self.user.is_authenticated():
            return 'foo'
        return 'bar'

    context_variable = self.get_context_variable()