【问题标题】:Failed load PDF from file DJANGO using embed tag使用嵌入标签从文件 DJANGO 加载 PDF 失败
【发布时间】:2021-05-12 03:33:16
【问题描述】:

我正在尝试加载 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 not found 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)

Settings.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 = '/'

【问题讨论】:

  • 可以发一下模特documento吗?还有你的根urls.py 只是为了看看你是否配置好了你的设置
  • @Lemayzeur 刚刚添加; documento => 我的模型中的课程
  • 你的根 urls.py 以及
  • ONLY IF DEBUG:你的 urls.py 中有这行吗:urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

标签: django pdf embed


【解决方案1】:

如果您的根目录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" />

【讨论】:

  • 只要按照你说的进行更改,但它会继续 GET 127.0.0.1:8000/INTRANET/uploads/curriculums/CV_2017.pdf 404 (Not Found)
  • 您能否在您的视图或 html 中 print(documento.adjunto.url ) &lt;h1&gt;{{ documento.adjunto.url }}&lt;/h1&gt; 向我展示您在控制台或浏览器中看到的内容。
  • Ubicacion 简历:{{documento.adjunto.url}}

    然后:Ubicacion 简历:/INTRANET/uploads/curriculums/CV_2017.pdf
  • 您的 settings.py 中的 MEDIA_ROOT 不正确,更新我的答案,检查一下
  • 工作!错误消失了,但仍然没有显示任何内容
【解决方案2】:

你也可以使用

doc = doc_models.objects.all()
<a href="{{doc.url}}">Pdf</a>

【讨论】:

    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多