具有Django url模式的位置参数

时间:2016-12-19 13:32:29

标签: python django django-urls url-pattern

我一直坚持这个Django错误:

  

tutorials()缺少1个必需的位置参数:'tutorial_id'

以下是文件。使用Python 3.5和Django 1.10。

教程/ urls.py

from django.conf.urls import url
from . import views

app_name = 'tutorials'

urlpatterns = [
    url(r'^(?P<tutorial_id>[0-9]+)/$', views.tutorials, name='tutorials'),
    url(r'^$', views.tutorials, name='tutorials'),
]

教程/ views.py

from django.shortcuts import render, get_object_or_404
from .models import Tutorial, Lesson

def tutorials(request, tutorial_id):
    tutorials = get_object_or_404(Tutorial, pk=tutorial_id)
    return render(request, 'tutorials/tutorials.html', { 'tutorials': tutorials})

当我访问website.com/tutorials时,我收到了错误,但如果我转到website.com/tutorials/1这很好的话,它会正常工作。但我希望能够访问/tutorials,以便我可以向此链接提供广告信息。

3 个答案:

答案 0 :(得分:0)

您需要通过模板中的url(1)传递此参数,或者在views.py(2)中为其创建默认值。

  1. {%url&#39;教程&#39; template.id%}
  2. def教程(request,tutorial_id = 1):

答案 1 :(得分:0)

也许你需要不同的功能来提供一系列教程和一个教程。

教程/ urls.py

from django.conf.urls import url
from . import views

app_name = 'tutorials'

urlpatterns = [
    url(r'^(?P<tutorial_id>[0-9]+)/$', views.tutorial_view, name='tutorials'),
    url(r'^$', views.tutorials_view, name='tutorials'),
]

教程/ views.py

from django.shortcuts import render, get_object_or_404
from .models import Tutorial, Lesson

def tutorials_view(request):
    tutorials = Tutorial.objects.all()
    return render(request, 'tutorials/tutorials.html', { 'tutorials': tutorials})

def tutorial_view(request, tutorial_id):
    tutorial = get_object_or_404(Tutorial, pk=tutorial_id)
    return render(request, 'tutorials/tutorial.html', { 'tutorial': tutorial})

您需要为单个教程视图创建单独的模板。

答案 2 :(得分:0)

由于django url模式排序,只需更改顺序,因为正则表达式^(?P<tutorial_id>[0-9]+)/匹配。选项包括:

将代码更改为

# tutorials_list is different view to handle list
urlpatterns = [
    url(r'^$', views.tutorials_list, name='tutorials-list'),
    url(r'^(?P<tutorial_id>[0-9]+)/$', views.tutorials, name='tutorials-detail'),
]

或在视图中查看

def tutorials(request, *args, **kwargs):
    tutorial_id = kwargs.get('tutorial_id', None)
    tutorials = get_object_or_404(Tutorial, pk=tutorial_id)
    return render(request, 'tutorials/tutorials.html', { 'tutorials': tutorials})

在url_patterns中定义了一个URL

urlpatterns = [
    url(r'^(?P<tutorial_id>[0-9]+)/$', views.tutorials, name='tutorials-detail'),
]