项目名称:JalaBapa_website
JalaBapa_website \网址:
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')
]
出版物/ 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.html
<div class="container-fluid">
{% for file_name in uploaded_file_names %}
<a href="{{ file_name }}">
<!-- <a href="{% url 'Publications:pdfs' file_name %}">
将继续......
上面的代码片段已经注释,因为在此之前显示错误:
/ publications /
的NoReverseMatch反向&lt; pdfs&#39;有参数&#39;(&#39; July_2017&#39;,)&#39;未找到。尝试了1种模式:[&#39;出版物/(?P ^ [A-Z] [a-z] + \ _ [0-9] {4} \。pdf $)&#39;]
Here is Error Screen Shot image
我想知道为什么这不起作用 - 问题1
ANYHOW,<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(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
网站时,它显示我的file_name:July_2017.pdf
与正则表达式匹配:^\[A-Z\]\[a-z\]+\_\[0-9\]{4}\.pdf$
答案 0 :(得分:0)
这可能不是答案 - 我对django不是很有信心,但我没有足够的声誉来发表评论。
问题1.你的插入符号('^')看起来与我的不同 - 我真的只把它看作是引号内的第一个字符(例如r'^ publications /(?P等等)我看不出这会导致问题,但可能需要尝试。
问题2,视图'pdfs'正在尝试提供FileResponse对象,但是你的文件名变量('July_2017')被剥去了'.pdf'扩展名,可以让它成功点击文件吗?