Django url正则表达式匹配但找不到页面错误
Posted
技术标签:
【中文标题】Django url正则表达式匹配但找不到页面错误【英文标题】:Django url regular expression matching but page not found error 【发布时间】:2018-02-27 11:48:36 【问题描述】:项目名称:JalaBapa_website
JalaBapa_网站\网址:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^about_us/', include('About_Us.urls')),
url(r'^activities/', include('Activities.urls')),
url(r'^collections/', include('Collections.urls')),
url(r'^contact_us/', include('Contact_Us.urls')),
url(r'^donate/', include('Donate.urls')),
url(r'^events/', include('Events.urls')),
url(r'^home/', include('Home.urls')),
url(r'^publications/', include('Publications.urls')),
]
出版物/urls.py:
from django.conf.urls import url
from . import views
app_name = "Publications"
urlpatterns = [
# /publications/
url(r'^$', views.publications, name='publications'),
# /publications/Xyz_9999.pdf/
url(r'(?P<file_name>^[A-Z][a-z]+\_[0-9]4\.pdf$)', views.pdfs, name='pdfs')
]
Publications/views.py
from django.http import HttpResponse, FileResponse
from django.shortcuts import get_object_or_404, render
from .models import *
# Create your views here.
def publications(request):
all_files = Publications.objects.all()
uploaded_file_names = []
for obj in all_files:
uploaded_file_names.append(str(obj.file_name()))
context =
'uploaded_file_names': uploaded_file_names
return render(request, 'publications/publications.html', context)
def pdfs(request, file_name):
with open('media/pdfs/'+file_name, 'r') as pdf:
response = FileResponse(pdf, content_type='application/pdf')
return response
一些代码:Publications/templates/publications/publications.html
<div class="container-fluid">
% for file_name in uploaded_file_names %
<a href=" file_name ">
<!-- <a href="% url 'Publications:pdfs' file_name %">
将继续...
sn-p 中的上述行已被注释,因为在此之前显示错误:
/publications/ 处的 NoReverseMatch
找不到带有参数“('July_2017',)'的'pdfs'的反向。尝试了 1 种模式:['publications/(?P^[A-Z][a-z]+\_[0-9]4\.pdf$)']
Here is Error Screen Shot image
我想知道为什么这不起作用 - 问题 1
无论如何,<a href=" file_name ">
是硬编码但正在运行,所以我暂时继续前进
将上面的文件继续向左半...
<div style="float: left;" class="boxes black-container text-grow">
file_name
</div>
</a>
% endfor %
</div>
问题 - 2:在上面的文件 publications.html 中,当我点击
file_name
时,它显示错误 404 页面未找到,here is screen shot of that page
链接:127.0.0.1:8000/publications/July_2017
url匹配的是:url(r'^publications/', include('Publications.urls'))
和url(r'(?P<file_name>^[A-Z][a-z]+\_[0-9]4\.pdf$)', views.pdfs, name='pdfs')
虽然,当我访问 https://www.regextester.com/88429
网站时,它显示我的文件名:July_2017.pdf
与正则表达式匹配:^\[A-Z\]\[a-z\]+\_\[0-9\]4\.pdf$
【问题讨论】:
【参考方案1】:这可能不是答案 - 我对 django 不是很有信心,但我没有足够的声誉来发表评论。
问题 1。插入符号 ('^') 的位置看起来与我的不同 - 我真的只将它视为引号内的第一个字符(例如 r'^publications/(?P 等)。我看不出这会导致问题,但可以尝试一下。
问题 2,视图“pdfs”正在尝试提供 FileResponse 对象,但您的文件名变量(“July_2017”)是否去掉了“.pdf”扩展名以使其能够成功访问文件?
【讨论】:
感谢 Atcrank,我也会尝试找出第一个问题的问题。以上是关于Django url正则表达式匹配但找不到页面错误的主要内容,如果未能解决你的问题,请参考以下文章