Django基于类的视图可处理多个查询

我正在将django函数视图重写为基于类的视图。我有这个当前功能

@login_required
def settings(request, template_name="settings.html"):
    context = {}

    context['kcs'] = KlarnaProfile.objects.filter(user_profile__user=request.user)
    context['extends'] = ExtendProfile.objects.filter(user_profile__user=request.user)
    context['fortnoxs'] = FortnoxProfile.objects.filter(user_profile__user=request.user)
    return render(request, template_name, context)

首先确认用户是否已登录,然后获取链接到该用户帐户的信息

这就是我基于班级的观点

class SettingsView(TemplateView):
    template_name = "settings.html"

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

如何添加将登录用户用作过滤器的三个过滤器?

评论
  • 语柳
    语柳 回复

    Use get_context_data method like this:

    class SettingsView(TemplateView):
        ...
    
        def get_context_data(self, **kwargs):
            context_data = super().get_context_data(**kwargs)
    
            context_data['kcs'] = KlarnaProfile.objects.filter(user_profile__user=self.request.user)
            ...
    
            return context_data
    

    整洁的选择。而不是做:

    class SettingsView(TemplateView):
        ...
    
        @method_decorator(login_required)
        def dispatch(self, *args, **kwargs):
            return super().dispatch(*args, **kwargs)
    

    你可以做:

    @method_decorator(login_required, name='dispatch')
    class SettingsView(TemplateView):
        ...
    

    You might want to read Decorating the class from Django's official documentation.

  • 浅唱夜旳美
    浅唱夜旳美 回复

    在视图中添加需要登录的mixin

    class LoginRequiredMixin(object):
        @classmethod
        def as_view(self, *args, **kwargs):
            view = super(LoginRequiredMixin, self).as_view(*args, **kwargs)
            return login_required(view)
    
        @method_decorator(login_required)
        def dispatch(self, request, *args, **kwargs):
            return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
    

    并如下修改视图。

    class SettingsView(LoginRequiredMixin, TemplateView):
        template_name = "settings.html"
    
        def get_context_data(self, **kwargs):
            context = super(SettingsView, self).get_context_data(**kwargs)
            context['kcs'] = KlarnaProfile.objects.filter(user_profile__user=request.user)
            context['extends'] = ExtendProfile.objects.filter(user_profile__user=request.user)
            context['fortnoxs'] = FortnoxProfile.objects.filter(user_profile__user=request.user)
            return context