多个参数url模式django 2.0

时间:2018-07-22 10:23:09

标签: python-3.x django-urls django-2.0

我想在我的url模式中传递两个参数,但是我遇到了错误,即反向匹配,即'projects'。虽然只有一个参数可以正常工作。

这是主网址文件-

-H 'Content-Type: application/json'

projects.urls-

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^materials/(?P<name>(\s+)/',include('materials.urls')),
    path(r'^projects/',include('projects.urls')),
]

views.py-

urlpatterns = [
path('',views.view_projects,name='view_projects'),
path('(?<projectid>\d+)/',views.project_steps,name='project_steps'),
path('(P<projectid>\d+)/(P<stepid>\d+)/',views.project_steps,
name='project_steps'),
] 

模板-

 def view_projects(request):
   projects = project.objects.all
   return render(request,'projects/project_view.html', 
   {'projects':projects})

def project_steps(request,projectid,stepno=1):
  projects = project.objects.all
  stepss = steps.objects.all
  return render(request,'projects/project_steps.html', 
  {'projectid':projectid,'steps':stepss,'projects':projects,
  'stepno':stepno})

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作。

Old Way
(r'^view_url/(\d+)/(\d+)$', r'app_name.views.view_function'),
def view_function(request, param1, param2):
    """
    :param request:
    :param param1:
    :param param2:
    :return:
    """
    return render('/* template path and parameters */')

New Way
(r'^view_url/<int:param1>/<int:param2>$', r'app_name.views.view_function'),
def view_function(request, param1, param2):
    """
    :param request:
    :param param1:
    :param param2:
    :return:
    """
    return render('/* template path and parameters */')

有关django 2.0中正则表达式模式的更多详细信息,您可以查看django文档链接。 https://docs.djangoproject.com/en/2.1/topics/http/urls/

答案 1 :(得分:0)

您可以轻松地(不使用正则表达式)来完成自己想要的事情。您可以找到documentation details here

path('some_page/<int:project_id>/', views.some_page, name='some_page'),

上面我的urlpattern的函数如下所示:

def some_page(request, project_id):
    project = Project.objects.get(id=project_id)
    return render(request, 'project.html', {'project': project})

请记住,您需要一个Project模型来使其正常工作,并且其中包含数据。

您的模板如下:

<p>{{ project.modelfieldname1 }}</p>
<p>{{ project.modelfieldname2 }}</p>

答案 2 :(得分:0)

无需匹配正则表达式或其他模型字段即可使其正常工作。

urls.py

path('custom_page/<str:id1>/<str:id2>/', views.custom_page, name='custom_page'),

views.py

def custom_page(request, id1, id2):
    #use in view func or pass to template via context
    context = {}
    context['id1'] = id1
    context['id2'] = id2
    return render(request, 'custom_page.html', context=context)

custom_page.html

<div>{{id1}} {{id2}}</div>