python-3.x 多参数链接模式django2.0

tcbh2hod  于 2022-12-24  发布在  Python
关注(0)|答案(4)|浏览(107)

我想在我的url模式中传递两个参数,但是我得到了错误的非反向匹配,即'项目'。虽然它只使用一个参数工作得很好。
这是主网址文件-

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

projects.urls-

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

views.py-

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

模板-

"{% url 'projects' projectid=project.id stepno=step.step_no %}"
h22fl7wq

h22fl7wq1#

不需要正则表达式匹配或额外的模型字段来使其工作。
第一个月

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>
olqngx59

olqngx592#

你可以做一些如下。

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 */')

更多关于django2.0正则表达式模式的细节,你可以查看django文档链接。https://docs.djangoproject.com/en/2.1/topics/http/urls/

wmtdaxz3

wmtdaxz33#

你可以更容易地做你想做的事情 (没有正则表达式),就像这样。你可以找到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>
k97glaaz

k97glaaz4#

我也有一个类似的实现,希望能对大家有所帮助。

Django模板(html文件)

<a href="{% url 'app:single-rfq' key='view' id=rfq.id %}">

应用程序URL文件

path('single-rfq/<str:key>/<int:id>/', views.single_rfq, name='single-rfq'),

视图文件

@login_required(login_url='/')    
def single_rfq(request, key, id):

相关问题