如何在Django中编写urlpatterns?

时间:2019-03-11 03:35:08

标签: python django django-urls

我有以下网址结构: page/section/subsection/article,其中sectionsubsectionarticle是用户生成的子弹名称。

如何写urlpatterns? 我这样做,但是可能存在更好的方法吗?

urlpatterns = [
    url(r'^$', views.index),
    url(r'^(?P<slug>[-\w]+)/$', views.section),
    url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/$', views.subsection),
    url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/(?P<articleslug>[-\w]+)/$', views.article)
]

我的观点:

def index(request):
    return render(request, 'MotherBeeApp/index.html', {})


def section(request, slug):
    sections = Section.objects.filter(page=slug)
    if sections:
        return render(request, 'MotherBeeApp/section.html', {'Sections': sections})
    else:
        return render(request, 'MotherBeeApp/404.html', status=404)


def subsection(request, slug, subslug):
    subsection = Section.objects.get(link_title=subslug)
    articles = Article.objects.filter(section=subsection.pk)
    page_title = subsection.title
    return render(request, 'MotherBeeApp/subsection.html', {'Articles': articles, 'PageTitle': page_title})


def article(request, slug, subslug, articleslug):
    article = Article.objects.get(link_title=articleslug)
    return render(request, 'MotherBeeApp/article.html', {'Article': article})

2 个答案:

答案 0 :(得分:1)

如果您使用的是比Django 2.0 <2.0 )更早的 Django版本,那么您在做正确的事情,并且已经在使用乐观的方式。但是如果您的 Django版本晚于或等于Django 2.0,则可以编写urlpatterns,如图here所示。

答案 1 :(得分:0)

也许您可以将Django升级到2.0+,然后使用以下代码:

from django.urls import path, include
urlpatterns = [
    path('', views.index),
    path('<slug:slug>/', include([
        path('', views.section),
        path('<slug:subslug>/', views.subsection),
        path('<slug:subslug>/<articleslug>/', views.article),
    ])),
]