尝试在 Django 中使用 ListView 进行分页时出现错误:“无法使用 None 作为查询值”

alc*_*der 4 python django django-views

我想在搜索结果中实现分页。搜索后我看到很好的结果(例如http://127.0.0.1:8001/search/?q=mos

但是,当我单击“下一步”时,出现错误:

/search/ 处出现 ValueError,请求 URL: http://127.0.0.1:8001/ search/?city=2

不能使用 None 作为查询值

我认为问题出在网址(search_results.html)。我该如何修复它?我该如何改变:

<a href="/search?city={{ page_obj.next_page_number }}">next</a>
Run Code Online (Sandbox Code Playgroud)

模型.py

from django.db import models

class City(models.Model):
    name = models.CharField(max_length=255)
    state = models.CharField(max_length=255)

    class Meta:
      verbose_name_plural = "cities"

    def __str__(self):
        return self.name
Run Code Online (Sandbox Code Playgroud)

视图.py

class HomePageView(ListView):
    model = City
    template_name = 'cities/home.html'
    paginate_by = 3
    page_kwarg = 'city'

def city_detail(request, pk):
    city = get_object_or_404(City, pk=pk)
    return render(request, 'cities/city_detail.html', {'city': city})


class SearchResultsView(ListView):
    model = City
    template_name = 'cities/search_results.html'
    paginate_by = 3
    page_kwarg = 'city'

    def get_queryset(self): # new
        query = self.request.GET.get('q')
        object_list = City.objects.filter(
            Q(name__icontains=query) | Q(state__icontains=query)
        )
        return object_list
Run Code Online (Sandbox Code Playgroud)

urls.py

urlpatterns = [
    path('search/', SearchResultsView.as_view(), name='search_results'),
    path('', HomePageView.as_view(), name='home'),
    path('city/<int:pk>/', views.city_detail, name='city_detail'),
]
Run Code Online (Sandbox Code Playgroud)

搜索结果.html

<ul>
  {% for city in object_list %}
    <li>
      {{ city.name }}, {{ city.state }}
    </li>
  {% endfor %}
</ul>

<div class="pagination">
    <span class="page-links">
        {% if page_obj.has_previous %}
            <a href="/search?city={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}
            <span class="page-current">
                Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
            </span>
        {% if page_obj.has_next %}
            <a href="/search?city={{ page_obj.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>
Run Code Online (Sandbox Code Playgroud)

首页.html

<form action="{% url 'search_results' %}" method="get">
  <input name="q" type="text" placeholder="Search...">
</form>

<ul>
  {% for city in object_list %}
    <li>
      <h1><a href="{% url 'city_detail' pk=city.pk %}">{{ city.name }}</a></h1>
    </li>
  {% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

Gil*_*rtS 6

您会收到一条错误消息,指出ValueError, query is None ,因为您没有在您的和锚标记q的 href 中传递查询。nextprevious

通过定义nextprevious锚标记来修改 search_results.html,如下所示:

<a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}">next</a>
Run Code Online (Sandbox Code Playgroud)

现在打开views.py。在 SearchResultsView 内部,您需要添加另一个query调用上下文字典的键。为此,请定义一个 get_context_data(self, **kwargs)在 SearchResultsView 类内部调用的方法。

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['query'] = self.request.GET.get('q')
        return context
Run Code Online (Sandbox Code Playgroud)

这样,query将被传递到模板中,以便您的 next链接看起来像http://localhost:8000/search/?city=2&q=a