【问题标题】:How to use get_queryset with Django DetailView with self.request.GET.get("q")如何将 get_queryset 与带有 self.request.GET.get("q") 的 Django DetailView 一起使用
【发布时间】:2019-05-30 14:23:50
【问题描述】:

我试图弄清楚如何将 get_queryset 与我的 Django detailview 结合起来。在正常用例中,我有这个工作,将 get_queryset 添加到 DetailView 和瞧!它可以工作....但是这个用例有点不同。

我正在使用 FormView 获取搜索值,然后在成功后返回详细视图。这也可以正常工作。当我尝试合并一个 get_queryset 来覆盖查询集时,就会出现问题。

这是我的代码:

表单视图

class AuthorSearchView(LoginRequiredMixin,FormView):
    form_class = AuthorSearchForm
    template_name = 'author_search.html'

    def get_form_kwargs(self):
        kwargs = super(AuthorSearchView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        kwargs['q'] = self.request.GET.get("q")
        return kwargs

然后在我的 author_search.html 中:

<form method="GET" autocomplete=off action="{% url 'Author:author_search_detail' %}">

当用户在搜索中输入一个值时……它会返回一个 DetailView 屏幕:

class AuthorSearchDetailView(LoginRequiredMixin,DetailView):
    model = Author
    context_object_name = 'author_detail'
    template_name = 'author_search_detail.html'

    def get_object(self, queryset=None):
        return get_object_or_404(Author, request_number=self.request.GET.get("q"))
        return get_object_or_404

上面的代码运行良好。注意我没有在我的操作参考中使用 PK 参考,因为这种方法不需要它。在上面的代码中,我的 URL 是:

url(r'^author_search_detail/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),

但是,当我尝试将 get_queryset 而不是 get_object 与以下代码合并时:

def get_queryset(self):
    queryset = super(AuthorSearchDetailView, self).get_queryset()
    return queryset.filter(request_number=self.request.GET.get("q"))

然后我得到:

AuthorSearchDetailView must be called with either an object pk or a slug in the URLconf.  

我知道这是因为我使用的是 DetailView 并且没有在我的 URL 中提供 PK。

但是,当我在我的 HTML 和我的 URL 中添加一个 pk 时,如下所示:

<form method="GET" autocomplete=off action="{% url 'Author:author_search_detail'pk=author.pk %}">

网址:

url(r'^author_search_detail/(?P<pk>\d+)/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),

我明白了……

Reverse for 'author_search_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['Author/author_search_detail/(?P<pk>\\d+)/$']

奇怪的是,如果我将 pk=author.pk 替换为 pk=user.pk,我不会收到错误消息。所以这让我相信,因为我最初使用 FormView 来获取 DetailView success_url...FormView 中的 pk 引用存在问题。不知道PK。

【问题讨论】:

    标签: django django-models django-forms django-templates django-views


    【解决方案1】:

    所以在想了太多之后……原来我想多了……

    我只需要将我的 get_object 更新为过滤条件...

    def get_object(self, queryset=None):
        return get_object_or_404(Author, request_number=self.request.GET.get("q"),user=self.request.user,id="1")
        return get_object_or_404
    

    在 get_object 的过滤条件中添加了用户和 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-30
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2014-01-21
      • 2014-02-13
      相关资源
      最近更新 更多