【问题标题】:get context data in get_queryset在 get_queryset 中获取上下文数据
【发布时间】:2021-03-30 22:25:16
【问题描述】:

我有 BaseContextListview 用于在多个模型中进行搜索,Search Class 继承自 BaseContext。我将当前用户设置为上下文,并希望在我的 def get_queryset 方法中使用它,但它不起作用。我认为在 Search CBV get_context_dataget_queryset 之后执行,这就是 self.user 为 None 的原因。

class BaseContext(ContextMixin):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        request = self.request
        if request.COOKIES.get('token') is not None:
            ...
            user = Users.objects.filter(user_id=user_id).first()
            context.update({'current_user': user})
            context.update({'is_logged_in ': True})
        else:
            context.update({'is_logged_in ': False})
        return context

class Search(BaseContext, ListView):
    template_name = 'search.html'
    context_object_name = "results"
    paginate_by = 15
    user = None

    def get_queryset(self):
        query = self.request.GET.get('search', None)
        if query is not None and self.user is not None:
            ...
            return queryset_chain
        return faqModel.objects.none()

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        if 'is_logged_in' in context and context['is_logged_in']:
            self.user = context['current_user']
        else:
            redirect("index")

        return context

我的问题是如何在 def get_queryset(self) 中获取上下文数据?

【问题讨论】:

  • 您没有使用标准方式访问当前用户的任何原因 - request.user?
  • 我的用户模型不同,与 Djang 用户模型无关

标签: python django


【解决方案1】:

对于 Listview get_quersyset() 在 get_contex_data() 之前调用,因此在 get_queryset() 中无法获取上下文数据

【讨论】:

  • 感谢回复,有没有办法访问上下文?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
相关资源
最近更新 更多