我正在嘗試允許用戶下載我之前MEDIA_ROOT通過管理控制臺上傳到檔案夾的 PDF 檔案。我已經模擬了這篇文章中的答案,但是它不完整,我不知道如何解決這個問題。希望有人能在下面的代碼中發現我的問題。
設定.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = str(BASE_DIR) "/media/"
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory that holds static files.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = str(BASE_DIR) "/static/"
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
模型.py
from django.db import models
# Create your models here.
class ResumeModel(models.Model):
pdf = models.FileField(upload_to="resume_app/media/resume/")
# So this file gets uploaded to root > media > resume_app > media > resume
管理員.py
from django.contrib import admin
from .models import ResumeModel
# Register your models here.
admin.site.register(ResumeModel)
視圖.py
from django.shortcuts import render
from .models import ResumeModel
# Create your views here.
def resume(request):
resume = ResumeModel.objects.all() # < Not sure if this part is needed?
return render(request, 'resume.html', context={'resume':resume})
模板.html
...
<a href="{{ resume.pdf.url }}">Click here to download PDF</a>
...
當我將滑鼠懸停在此鏈接上時,它指向的 url 是localhost:8083/resume/我們當前所在頁面的名稱,所以我認為<a href="{{ resume.pdf.url }}">它沒有指向我上傳的 PDF 檔案的正確 url。上傳確實有效,檔案在root > media > resume_app > media > resume檔案夾中。我需要什么才能使鏈接正常作業?
更新
感謝下面@tonio 的幫助,除了我的疏忽之外,我更改了以下行:
def resume(request):
resume = ResumeModel.objects.all() # < Not sure if this part is needed?
return render(request, 'resume.html', context={'resume':resume})
至
def resume(request):
resume = ResumeModel.objects.last()
return render(request, 'resume.html', context={'resume':resume})
...這對我來說很好,因為我那里只有一份簡歷,最后一個條目將是最近上傳的。然后我進入該應用程式的檔案夾,洗掉__pycache__andmigrations檔案夾,執行python manage.py makemigrations resume_appand python manage.py migrate resume_app,重新啟動服務器,在隱身視窗中打開應用程式,它可以正常作業!
uj5u.com熱心網友回復:
您將存盤在資料庫中的所有簡歷物件發送到模板:
resume = ResumeModel.objects.all()
您可以發送由其主鍵標識的特定簡歷(請參閱此):
def resume(request, resume_id):
resume = get_object_or_404(ResumeModel, resume_id)
return render(request, 'resume.html', context={'resume':resume})
無論如何,您可以測驗發送資料庫中第一份簡歷的模板:
def resume(request):
resume = ResumeModel.objects.first()
return render(request, 'resume.html', context={'resume':resume})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/493903.html
下一篇:編碼-字串位元組長度
