()缺少1个必需的位置参数:“ id”

时间:2018-10-21 09:54:42

标签: python django django-urls

尝试显示单个项目时,我总是收到错误消息。 这是我的代码,我希望它是可以理解的。我正在使用Django 1.11

1。我的网址页面:

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/', views.aboutus, name='aboutus'),
url(r'^specialoffers/', views.offers, name='offers'),
url(r'^contactus/', views.contact, name='contact'),
url(r'^excursions/', views.excursions, name='excursions'),
url(r'^singleexcursion/<int:id>/', views.singleexcur, name='singleexcur'),
url(r'^booking/', views.booking, name='booking'),
url(r'^confirmation/', views.confirming, name='confirming'),
url(r'^payment/', views.payment, name='payment'),

]

  1. 我的视图页面:

    def singleexcur(request,id):

    excur = Excursion.objects.get(id = id)
    
    
    return render(request, "excursions/single.html", {"excur": excur })
    
  2. 我的错误: / singleexcursion //处的TypeError singleexcur()缺少1个必需的位置参数:'id'

2 个答案:

答案 0 :(得分:0)

处理空ID的一种简单方法是使用多个网址进行游览:

 url(r'^singleexcursion/', views.singleexcur, name='singleexcur'),
 url(r'^singleexcursion/<int:id>/', views.singleexcur, name='singleexcur'),

答案 1 :(得分:0)

开始,引入了新的语法,因此您可以编写类似<int:id>的参数,但这在url(..)构造中适用,此处您需要使用类似于regex的语法编写路径,因此可以将URL指定为:

# before Django-2.0

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^about/$', views.aboutus, name='aboutus'),
    url(r'^specialoffers/$', views.offers, name='offers'),
    url(r'^contactus/$', views.contact, name='contact'),
    url(r'^excursions/$', views.excursions, name='excursions'),
    url(r'^singleexcursion/(?P<id>\d+)/', views.singleexcur, name='singleexcur'),
    url(r'^booking/$', views.booking, name='booking'),
    url(r'^confirmation/$', views.confirming, name='confirming'),
    url(r'^payment/$', views.payment, name='payment'),
]

或者在及更高版本中,您可以使用path(..) [Django-doc]。您可以将其与re_path(..) [Django-doc]进行交织,这是url(..)的新名称,因为url(..) [Django-doc]最终可能会被删除。

例如:

# Django-2.0 and above

urlpatterns = [
    re_path(r'^$', views.home, name='home'),
    re_path(r'^about/$', views.aboutus, name='aboutus'),
    re_path(r'^specialoffers/$', views.offers, name='offers'),
    re_path(r'^contactus/$', views.contact, name='contact'),
    re_path(r'^excursions/$', views.excursions, name='excursions'),
    path('singleexcursion/<int:id>/', views.singleexcur, name='singleexcur'),
    re_path(r'^booking/$', views.booking, name='booking'),
    re_path(r'^confirmation/$', views.confirming, name='confirming'),
    re_path(r'^payment/$', views.payment, name='payment'),
]