【问题标题】:Django File Field in model模型中的 Django 文件字段
【发布时间】:2018-10-11 03:00:26
【问题描述】:

我正在尝试显示我在模型中上传的 HTML 文件。目前,使用{{ object.file.url }} 语法只是显示文件的路径。我想显示文件本身。

唯一的附加部分是我已经解决了我的MEDIA_ROOT 并添加到了我的网址:

 if settings.DEBUG:
       urlpatterns += 
       static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
       urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

现在,url 显示为folder/file.html。希望将该文件用作较大模型的列表和详细视图的一部分。

【问题讨论】:

  • 我猜你想将 HTML file 然后 response 呈现给浏览器。我说的对吗?
  • 是的,我想要一个渲染文件的详细视图
  • 好的,我不确定我是否理解使用通用视图时这将如何工作。我应该把render放在哪里?

标签: django django-models django-views


【解决方案1】:

我还没有尝试过,但至少你应该明白这一点。 假设你有FielField,你需要渲染来自record 的值。您可能需要使用Class-Based Views,因为它有许多现成的功能。

models.py

from django.db import models


class DjFile(models.Model):
    title = models.CharField()
    file = models.FileField(upload_to='files')

views.py

from django.shortcuts import render, get_object_or_404

# Function-Based View
from djfiles.models import DjFile


def dj_view(request, pk=None):
    """Get the record and render the `file`"""
    obj = get_object_or_404(DjFile, pk=pk)
    return render(request, obj.file, {
        'title': obj.title
    }, content_type='application/xhtml+xml')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 2021-03-30
    • 2022-06-16
    • 2019-12-24
    • 1970-01-01
    • 2013-02-03
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多