【问题标题】:getting NoReverseMatch for a correct url and correct arguments为正确的 url 和正确的参数获取 NoReverseMatch
【发布时间】:2018-06-13 06:22:39
【问题描述】:

我已经彻底查看了我的代码,但我仍然卡在这一点上,我得到正确的 url 和正确的参数的 NoReverseMatch 错误。

这是我的 URLConfig

 url(r'profile/$', views.agent_profile, name='agent_profile'),
        url(r'profile/(?P<pk>[A-Za-z0-9]+)/$', views.change_profile, name='change_profile'),
        url(r'assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$', views.assign_profile, name='assign_profile'),

处理该请求的视图是:

def assign_profile(request, pk, profile):
    agent = Agent.objects.get(pk=pk)
    # profile = Profile.objects.filter(designation=profile)
    # profile.agents = agent
    return render(request,
                    'portfolio/change_profile.html',
                    {'agent': agent})

模板中的url调用如下:

<li><a href={% url 'portfolio:assign_profile' pk=agent.code_agent profile="super_agent" %}>Super Agent</a></li>

错误如下:

NoReverseMatch at /portfolio/profile/1/
Reverse for 'assign_profile' with keyword arguments '{'pk': '1', 'profile': 'super_agent'}' not found. 1 pattern(s) tried: ['portfolio/assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$']
Request Method: GET
Request URL:    http://localhost:8000/portfolio/profile/1/
Django Version: 1.11
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'assign_profile' with keyword arguments '{'pk': '1', 'profile': 'super_agent'}' not found. 1 pattern(s) tried: ['portfolio/assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$']
Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497
Python Executable:  C:\Users\admin\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.1
Python Path:    
['C:\\Users\\admin\\PycharmProjects\\trial',
 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib',
 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36',
 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
Server time:    Wed, 3 Jan 2018 14:35:49 +0000

【问题讨论】:

    标签: python django


    【解决方案1】:

    您有 profile="super_agent",但在您的正则表达式中 [A-Za-z0-9_]+ 不包含下划线。

    url(r'assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9_]+)/$', views.assign_profile, name='assign_profile'),
    

    您还可以使用[\w-]+,它匹配大写字母 A-Z、小写字母 a-z、数字 0-9、连字符和下划线。如果你的主键是一个整数,那么[0-9]+ 就足够了。综上所述,您有:

    url(r'assign/(?P<pk>[0-9]+)/profile/(?P<profile>[\w-]+)/$', views.assign_profile, name='assign_profile'),
    

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多