ใช้แพ็กเกจ django-downloadview ทำให้ไฟล์ในโปรเจกต์ดาวน์โหลดได้ สามารถโฮสต์ไฟล์บนเซิร์ฟเวอร์
บทความนี้สอนทำให้ไฟล์ดาวน์โหลดได้ใน Django
ตัวอย่าง
ติดตั้งแพ็กเกจ:
pip install django-downloadview
สร้างโปรเจกต์และแอป ตั้งค่า urls เพิ่มแอปใน INSTALLED_APPS ตั้งค่า MEDIA_ROOT และ MEDIA_URL ใน settings.py
ใน models.py:
from django.db import models
class Data(models.Model):
file = models.FileField(upload_to='myfiles/', blank=True)
สร้างโมเดลเก็บ reference ไฟล์ที่อัปโหลด สร้าง dummy data
ใน urls.py:
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django_downloadview import ObjectDownloadView
from .models import Data
download = ObjectDownloadView.as_view(model=Data, file_field='file')
urlpatterns = [
path('', views.home, name="home"),
path('download//', download, name="default"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
สร้าง 2 endpoints: หน้าแรก และ download view ObjectDownloadView รับโมเดลและฟิลด์ไฟล์
ใน views.py:
def home(request):
return render(request, 'home.html')
ใน home.html:
<!DOCTYPE html> <html>
<head> <title>TUT</title> </head>
<body>
<h2>HI</h2>
<a href="https://127.0.0.1:8000/download/1/">Download</a> // '1' คือ ID ของ dummy data
</body> </html>
เอาต์พุต
