Hello everyone, I am new to Django. Now I want to learn to make a download function. Set up a hyperlink in the front-end html, get the file name through the background access method and download it.
The code is as follows:
Front desk: (relatively simple, just a table with hyperlinked words)
URL configuration:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^register/',views.userRigister,name='register'),
url(r'^register/(.*)/$',views.file_download,name='download'),
]
VIEW method:
def userRigister(req):
status='welcome'
#js alert出信息
return render(req, 'register.html', {'status':json.dumps(status)})
def file_download(request,filename):
print(filename)
def file_iterator(file_name, chunk_size=1024):
with open(file_name) as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
if os.path.exists('software/' + filename):
the_file_name = filename
response = StreamingHttpResponse(file_iterator(the_file_name))
return response
else:
return HttpResponse('error!no such file!')
My purpose is to select a downloadable browser when visiting the same page normally. After clicking the hyperlink button, access the file_download
method and download the corresponding browser. However, the file_download
method is currently unavailable, so please give me some advice. Thank you
阿神2017-05-18 10:58:48
Django matches URLs from top to bottom in the URL list
Anything that can be matched by ^register/(.*)/$
must be matched by the above ^register/< /code> matches
^register/(.*)/$
匹配的一定能被上面的^register/
匹配
所以就出现了^register/(.*)/$
So there is a situation where ^register/(.*)/$
never matches
The solution is very simple, just change the order of these two
url(r'^admin/', admin.site.urls),
url(r'^register/(.*)/$',views.file_download,name='download'),
url(r'^register/',views.userRigister,name='register'),
When using Django’s URL parsing function, remember that more detailed URLs should be placed farther forward, and more “blurred” URLs should be placed farther back.