在我的应用程序中,我想显示一个基于特定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')),
]
餐馆/网址.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()),
]
餐馆/景观.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错误,而不是所有餐馆的列表,我不知道为什么。你们能帮我吗?
似乎是一个url问题。在你的restaunts/url.py中,你需要为它添加一个url。
urlpatterns = [
url(r'^$', RestaurantLocationListView.as_view()), # add it before
url(r'^(?P<slug>w+)/$', RestaurantLocationListView.as_view()),
]