首页 > 解决方案 > 使用嵌入标签从文件 DJANGO 加载 PDF 失败

问题描述

我正在尝试加载 PDF

我的.html

<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <embed src="{{ documento.adjunto.url }}" type="application/pdf" width="100%" height="600px" />
        </div>>
    </div>
</div>

其中 documento.adjunto 是保存文档的 url(在我的例子中是“curriculums/CV_2017.pdf”)

它让我无法加载资源:找不到 404 http://127.0.0.1:8000/INTRANET/uploads/curriculums/CV_2017.pdf

但是有保存PDF的地方

模型:

UPLOAD_CVS = "curriculums/"
class Curriculum(models.Model):
    rut_candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE)
    adjunto = models.FileField(upload_to=UPLOAD_CVS)
    fecha_ingreso_cv = models.DateField(_("Date"), auto_now_add=True)

    def get_ultima_actualizacion(self):
        actual = datetime.now().date()
        return int(round((actual - self.fecha_ingreso_cv).days / 365,0))

    def get_cv_name(self):
        return 
       "CV_"+self.rut_candidato.nombre+"_"+self.rut_candidato.apellido+"_"+ str(self.fecha_ingreso_cv)

设置.py:

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = []



INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'INTRANET.apps.IntranetConfig',
    'localflavor',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'etalentNET.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['./templates',],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.media',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'etalentNET.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'

#Cambiar a chile
TIME_ZONE = 'Chile/Continental'

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_URL = '/INTRANET/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'INTRANET/uploads')
STATIC_URL = '/static/'

# Por ahora, mientras no se configure envio email https://docs.djangoproject.com/en/2.0/topics/email/
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Redirect to home URL after login (Default redirects to /accounts/profile/)
LOGIN_REDIRECT_URL = '/'

标签: djangopdfembed

解决方案


如果您的根目录中没有此行,请urls.py添加它

urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

注意:这仅在开发中有效

MEDIA_URL应该以/.
所以,而不是MEDIA_URL = 'INTRANET/uploads/',添加这个:

MEDIA_URL = '/INTRANET/uploads/' 
MEDIA_ROOT = os.path.join(BASE_DIR, 'INTRANET/uploads') # no Slash before  and after

在模板中,你甚至不需要添加路径,Django 会生成它:而不是../uploads/{{ documento.adjunto }},添加{{ documento.adjunto.url }}

<embed src="{{ documento.adjunto.url }}"
       type="application/pdf" width="100%" height="600px" />

推荐阅读