如何用Django编写urlpatterns?

2024-09-30 16:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的URL结构: page/section/subsection/article,其中sectionsubsectionarticle是用户生成的slug名称。你知道吗

如何编写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})

Tags: urlreturntitlerequestdefhtmlarticlepage
2条回答

也许您可以将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),
    ])),
]

如果您使用的是早于Django 2.0<;2.0)的Django版本,那么您就是在做正确的事情,而且您已经在使用乐观的方式了。但是如果您的Django版本晚于或等于Django 2.0,您可以编写urlpatterns,如here所示。你知道吗

相关问题 更多 >