我有一个名为“ my_project”的项目,在该项目中,我有一个名为“ my_app”的应用程序,因此我有两个urls.py文件。我的所有my_app网址都位于其urls.py文件中,并且可以正常工作,除了一个。那就是“ download_file”。当它包含在my_project的urls.py中时,我的网站可以工作,但是当它位于my_app的urls.py中时NoReverseMatch
,页面加载时出现错误。
我不知道为什么该URL仅在位于我的主项目URL的文件夹中时才起作用。我怀疑它与正则表达式有关,尽管我无法弄清楚。
用户将在此页面上:
http://127.0.0.1:8000/user_area/username/classes
然后点击“下载”链接:
<a href="{% url 'download_file' file_path=item.instance.user_file %}" target='_blank'>{{ item.instance.filename }}</a>
my_project.py
urlpatterns = [
# reference to my_app
re_path(r'^user_area/(?P<username>[\w-]+)/', include('my_app.urls')),
]
# this works
url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'),
]
my_app.py
urlpatterns = [
path('classes', views.classes, name='classes'),
# if I remove the url from my_project.py this one returns NoReverseMatch on page load
url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'),
谢谢。
发生问题是因为您的网址模板标记仅提供了一个参数:file_path
。
在项目urls.py中声明URL时,此方法有效,因为仅需要一个参数。
当您尝试使用中的URL时my_app.urls
,还需要提供username
参数。您将需要使用类似:
<a href="{% url 'download_file' username=request.user.username file_path=item.instance.user_file %}" target='_blank'>{{ item.instance.filename }}</a>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句