我試圖將搜索功能添加到我的網站,但我遇到了一些問題。目前它告訴我「搜索」沒有定義,但我的視圖文件中有類。這是我迄今: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
任何見解是極大的讚賞。我只是一點一點地拼湊這些東西。謝謝!
導入視圖是不夠的;你需要導入'Search'類,就像這樣:'from views import Search' –
@JohnGordon當我嘗試的時候,我得到一個導入錯誤,提示「No module named views」。 – SepticReVo
你應該將urls.py Search.as_view()替換爲views.Search.as_view() –