我已经彻底查看了我的代码但是我仍然停留在这一点,我得到NoReverseMatch错误以获取正确的url和正确的参数。
这是我的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
答案 0 :(得分:2)
您有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'),