iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
Modern Web

Python x Django 網站實作&學習記錄系列 第 15

D15 下載功能測試

一樣先確認使用者在文件庫有哪些文件
確認傳送來的文件doc_id是屬於使用者
確認文件存在後回傳HttpResponse給使用者下載
doc_info/views.py

@login_required
def doc_download(request,doc_id):
    user = request.user
    Doc_warehouse = doc_warehouse.objects.filter(user_id=user.id)
    try:
        doc = Doc_warehouse.get(id=doc_id)
        upload_file_path = str(doc.upload_file)
        print(upload_file_path)
        if os.path.exists(upload_file_path):
            with open(upload_file_path, 'rb') as file:
                response = HttpResponse(file.read(), content_type="application/vnd.ms-excel")
                response['Content-Disposition'] = f"inline; filename={os.path.basename(upload_file_path)}"
                return response
    except Exception as e:
        print(e)
        return HttpResponseNotFound('You have no access to this file')

網址會去抓downlaod/doc_id參數
doc_info/urls.py

from django.urls import path
from . import views

app_name = "doc_info"
urlpatterns = [
    path('doc/download/<int:doc_id>', views.doc_download, name='download'),
]

在使用者個人文件頁新增table欄位
超連結將文件的doc_id傳到下載功能的網址
templates/doc/user_list.html

{% block content %}

<a href="{% url 'doc_info:main' %}">Main page</a> |
<a href="{% url 'auth_info:profile' %}">My Profile</a> | 
<a href="{% url 'account_logout' %}">Logout</a>

<p>Welcome {{ user.first_name }} {{ user.last_name }}</p>

<a href="{% url 'doc_info:create' %}">Create document</a>
<p></p>

<table border = "1">
    <thead>
        <tr>
            <th >Create date: </th>
            <th>Last modified date:</th>
            <th>Author</th>
            <th>Title</th>
            <th>Remark</th>
            <th>Attachment</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
     {% for doc in Doc_warehouse %}
        <tr>
            <td>{{ doc.create_date }}</td>
            <td>{{ doc.last_mod_date }}</td>
            <td>{{ doc.user }}</td>
            <td>{{ doc.title }}</td>
            <td>{{ doc.remark }}</td>
            <td><a href="{% url 'doc_info:download' doc_id=doc.id %}">{{ doc.upload_file_name}}</a></td>
            <td><a href="{% url 'doc_info:delete' doc_id=doc.id %}" onclick="return confirm('Are you sure you want to delete this?')">Delete</a></td>
     {% endfor %}
        </tr>
    </tbody>
  </table>


{% endblock %}

上一篇
D14 重新設定create date & 上傳功能測試
下一篇
D16 文件創建頁 Create doc
系列文
Python x Django 網站實作&學習記錄30

尚未有邦友留言

立即登入留言