用"空塞"找不到页面Django上的模式

时间:2017-08-31 23:50:10

标签: python django python-3.x

在我的应用程序中,我想显示基于某个URL的项目列表。例如,当我输入mysite.com/restaurants/chinese/时,我想展示所有的中国餐馆。如果我输入mysite.com/restaurants/american/,我想展示所有美国餐馆等等。但是当我输入mysite.com/restaurants/我想要显示所有的餐馆,所以我写了这段代码:

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错误而不是所有餐馆的列表,我不知道为什么。你们能帮助我吗?

1 个答案:

答案 0 :(得分:4)

似乎是一个网址问题。在你的restaraunts / url.py中你需要为它添加一个URL。

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