在Django站点上搜索功能

时间:2016-08-23 03:34:55

标签: python django

我试图在我的网站上添加搜索功能,但我遇到了一些问题。它目前告诉我"搜索"没有定义,但我在我的视图文件中有类。这就是我到目前为止所做的:

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^player/(?P<pk>\d+)/$', views.player, name='player'),
    url(r'^season/(?P<pk>\d+)/$', views.season, name='season'),
    url(r'^seasons/$', views.seasons, name='seasons'),
    url(r'^search/$', Search.as_view(), name='search'),
]

views.py

from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView
from .models import Player, Season, PxS, Statistics

def home(request):
    seasons = Season.objects.order_by('sid')
    return render(request, 'webapp/home.html', {'seasons': seasons})

def player(request, pk):
    player = get_object_or_404(Player, pk=pk)
    return render(request, 'webapp/player.html', {'player': player, 'seasons': player.season_set.order_by('sid'), 'statistics': player.statistics_set.all()})

def season(request, pk):
    season = get_object_or_404(Season, pk=pk) 
    return render(
        request, 
        'webapp/season.html',
        {'season': season, 'players': season.players.order_by('lastname')}
    )

def seasons(request):
    seasons = Season.objects.order_by('sid')
    return render(request, 'webapp/seasons.html', {'seasons': seasons})

class Search(ListView):
    template_name = 'search.html'
    model = Player
    context_object_name = 'list'

    def get_context_data(self, **kwargs):
        context = super(Search, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context

    def get_queryset(self):
        pobj = Player.objects.all()
        var_get_search = self.request.GET.get('search_box')
        var_get_order_by = self.request.GET.get('pid')

        if var_get_search is not None:
            pobj = pobj.filter(playername__icontains=var_get_search)

        if var_get_order_by is not None:
            pobj = pobj.order_by(var_get_order_by)

        return pobj

非常感谢任何见解。我只是一点一点地拼凑这些东西。谢谢!

1 个答案:

答案 0 :(得分:3)

问题出在urls.py

提供网址(r&#39; ^搜索/ $&#39;,views.Search.as_view(),name =&#39;搜索&#39;),

而不仅仅是搜索。