2017-08-31 75 views
0

在我的应用程序中,我想根据某个url显示项目列表。例如,当我输入mysite.com/restaurants/chinese/时,我想要显示所有的中餐馆。如果我输入mysite.com/restaurants/american/,我想显示所有美国餐馆等。但是,当我键入mysite.com/restaurants/我想告诉所有的餐馆,所以我写了这个代码:在Django上找不到与“空slu”“模式的页面

urls.py

from django.conf.urls import url, include 
from django.contrib import admin 


urlpatterns = [ 
    url(r'^admin/', admin.site.urls), 
    url(r'^restaurants/', include('restaurants.urls')), 
] 

餐厅/ urls.py

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

from .views import RestaurantLocationListView 

urlpatterns = [ 
    url(r'^(?P<slug>\w+)/$', RestaurantLocationListView.as_view()), 
] 

餐厅/ views.py

from django.db.models import Q 
from django.shortcuts import render 
from django.views.generic import ListView 

from .models import RestaurantLocation 

class RestaurantLocationListView(ListView): 
    def get_queryset(self): 
     slug = self.kwargs.get('slug') 

     if slug: 
      queryset = RestaurantLocation.objects.filter(
       Q(category__iexact=slug) | Q(category__icontains=slug) 
      ) 
     else: 
      queryset = RestaurantLocation.objects.all() 

     return queryset 

这一切运作良好,除非我只放mysite.com/restaurants/。这给我一个404错误,而不是所有餐馆的列表,我不知道为什么。你们能帮我吗?

回答

4

看起来像一个URL问题。在您的restaraunts/url.py中,您需要为其添加网址。

urlpatterns = [ 
    url(r'^$', RestaurantLocationListView.as_view()), # add it before 
    url(r'^(?P<slug>\w+)/$', RestaurantLocationListView.as_view()), 
] 
+0

它的工作,谢谢。但你知道这是为什么发生吗? – flpn

+1

@flpn'mysite.com/restaurants /'不匹配''^(?P \ w +)/ $'',因为有一个强制的'w +'。 –