Django url 模式的位置参数

Positional Arguments withDjango url patterns

我被这个 Django 错误困住了一段时间:

tutorials() missing 1 required positional argument: 'tutorial_id'

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

tutorials/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'),
]

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 以便我可以向此 link.

添加信息

您需要在模板中通过 url (1) 传递此参数,或在 views.py (2) 中为它设置默认值。

  1. {% url 'tutorials' template.id %}
  2. def 教程(请求,tutorial_id=1):

也许您需要不同的函数来为教程集合和单个教程提供服务。

tutorials/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'),
]

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})

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

是因为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 定义的 int url_patterns

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