我正在尝试允许用户下载我以前通过管理控制台上传到MEDIA_ROOT文件夹的PDF文件。我在这个职位中模拟了答案,但是它是不完整的,我不知道如何解决这个问题。希望有人能在下面的代码中发现我的问题。
settings.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/'models.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 > resumeadmin.py
from django.contrib import admin
from .models import ResumeModel
# Register your models here.
admin.site.register(ResumeModel)views.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})template.html
...
<a href="{{ resume.pdf.url }}">Click here to download PDF</a>
...当我悬停在这个链接上时,它指向的url是localhost:8083/resume/,它是我们当前所在页面的名称,所以我认为<a href="{{ resume.pdf.url }}">没有指向我上传的PDF文件的正确网址。上传工作,文件在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})...which对我来说很好,因为我将只有一份简历在那里,最后一项将是最近的上传。然后我进入了应用程序的文件夹,删除了__pycache__和migrations文件夹,执行了python manage.py makemigrations resume_app和python manage.py migrate resume_app,重新启动了服务器,在匿名窗口中打开了应用程序,并且按需要工作!
发布于 2022-06-21 06:28:44
将存储在数据库中的所有简历对象发送到模板:
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://stackoverflow.com/questions/72694884
复制相似问题