【问题标题】:Files in django templatedjango 模板中的文件
【发布时间】:2020-12-20 20:27:48
【问题描述】:

当我尝试在 django 模板中显示文件下载链接时遇到问题

消息:

AttributeError: 'NoneType' object has no attribute 'split'
  File "c:\users\ramin\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
----------------------------------------
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------

models.py:

from django.db import models

class Book(models.Model):
    Title = models.CharField(max_length=100)
    Writer = models.CharField(max_length=100)
    Description = models.TextField()
    Image = models.ImageField(default='default.jpg')
    File = models.FileField(upload_to='PDF/')

    def __str__(self):
        return self.Title

views.py:

from django.views.generic.list import ListView
from . import models

class BookListView(ListView):
    queryset = models.Book.objects.all()
    template_name = 'Book/BookList.html'

模板:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Books List</title>
</head>
<body>
    {% for x in object_list %}
        <h2><a href="">{{ x.Title }}</a></h2>
        <img style="width:100px" src="{{ x.Image.url }}">
        <p><a href="{{ x.File.url }}" download="{{ x.Title }}">Download</p>
    {% endfor %}
</body>
</html>

当我点击下载链接时,我可以成功下载文件,但我看到了这条消息

【问题讨论】:

  • simple_server.py

标签: python django django-models django-views django-templates


【解决方案1】:

可能是你使用.txt文件作为默认图片的问题

【讨论】:

  • 这是写问题时的打字问题:)
  • 这是一个奇怪的问题...尝试使链接在新选项卡中打开。我不认为这是代码问题
【解决方案2】:

尝试以下代码,假设 object_name 是该模型的对象:

filename = os.path.basename(object_name.file.name)
response = HttpResponse(object_name.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % filename

return response

有关直接发送文件,请参阅 Django 文档的以下部分:https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

【讨论】:

    猜你喜欢
    • 2011-07-10
    • 2013-03-28
    • 2016-08-02
    • 2013-03-02
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    相关资源
    最近更新 更多