1
我的網站針對不同的類別擁有不同的網址,這些網址會根據類別返回一個已過濾的查詢集。 /sport/
將返回Post.objects.filter(category='sport')
試圖管理我的網址
網址
urlpatterns = [
url(r'^news/$', boxes_view, name='news'),
url(r'^sport/$', boxes_view, name='sport'),
url(r'^technology/$', boxes_view, name='technology'),
url(r'^science/$', boxes_view, name='science'),
url(r'^cars/$', boxes_view, name='cars'),
url(r'^television/$', boxes_view, name='television'),
url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'),
視圖
def boxes_view(request):
category = 'news'
for a, b in CATEGORY_CHOICES:
name = resolve(request.path_info).url_name
if b == name:
category = a
posts = Post.objects.all().filter(category=category)
choices.py
CATEGORY_CHOICES = (
('1', 'news'),
('2', 'sport'),
('3', 'technology'),
('4', 'science'),
('5', 'cars'),
('6', 'television')
)
來取代列出我的網址每一個類別,反正是有,我可以只寫1個統一的url模式來解決所有這些問題?
你如何獲得你的try/except代碼中的類別值?目前我通過獲取url路徑的最後一個字來獲取它,但我無法看到如何使用'category_number = CATEGORY_MAP [category]' – Zorgan
將類別傳遞到視圖中,作爲視圖函數的參數。當你在Django url模式中使用正則表達式時會發生這種情況。 – ChidG
url模式在哪裏得到'category'?它是否會像{%url'boxes_view'category ='sport'%}''{%url'boxes_view'category ='technology'%}'? – Zorgan