【问题标题】:SQLite django download not showing fileSQLite django 下载不显示文件
【发布时间】:2020-07-02 16:24:36
【问题描述】:

我无法使用 django 从我的 sqlite 数据库下载文件。 我创建了一个数据库模型。然后我进入我的 django 管理员并上传了文件。 然后在index.html我设置了下载链接。但是,当我按下下载链接时,我的页面似乎只是刷新并且没有下载。我创建的应用程序名为chartsapp。也许这与我的代码行 {{ chartsapp.the_file.url }} 有关。我已经尝试过the_file.url,但这似乎也没有任何作用。有什么建议吗?

模型.PY

from django.db import models

class Datahere(models.Model):
    text = models.FileField(upload_to='Uploaded')

管理员.PY

from django.contrib import admin
from .models import Datahere

admin.site.register(Datahere)

索引.HTML

<a href="{{ chartsapp.the_file.url }}">Download the file</a>

URLS.PY

urlpatterns = [
    path('', views.index, name="index"),

]

VIEWS.PY

from django.shortcuts import render
from .models import Datahere

def index(request):
    model = Datahere
    return render(request, "index.html", {})

【问题讨论】:

  • {{ chartsapp.the_file.url }} 应该如何工作?你网站的逻辑是什么?你能分享一下你的看法吗
  • 我以为这会打开数据库中文件的绝对路径?因此打开文件?我刚开始,所以真的不知道我在做什么。

标签: html django database sqlite


【解决方案1】:

好吧,我仍然是 django 的初学者,但是如果你想让你的 url 正常工作,你必须将 url 添加到 urls.py 文件中,然后在 views.py 中进行编辑。 我希望这会有所帮助。

【讨论】:

  • 我在问题中添加了我的urls.pyviews.py
  • 哦,我错过了那个对不起
  • 我对 django 的一些信息的最后回答,再次抱歉,我仍在学习,在终端执行 python manage.py makemigration,之后 python manage.py migrate。
  • 转到包含 manage.py 文件的文件夹,然后重试上一个答案中的两个命令
【解决方案2】:

首先,您不会从您的 sqlite 数据库中下载文件。相反,您的模型会保存任何文件/图像/等。到 MEDIA_ROOT/UploadedMEDIA_ROOT 在您的 settings.py 中定义,如下所示:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

数据库本身根本不存储媒体文件(和静态文件)。它只是将文件的位置存储为相对于MEDIA_ROOT 的路径。

因此,要根据需要在模板中呈现指向文件的链接,您可以像这样继续:

{% load static %}
<body data-media-url="{% get_media_prefix as MEDIA_PREFIX %}">

<img src="{{ MEDIA_PREFIX }}images/your_image.png">

or 

<a href="{{ MEDIA_PREFIX }}pdfs/your_file.pdf">Download the file</a>

只要在开发中,您还需要将网址添加到 yoururls.py,如下所示:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] 

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

您还应该考虑在存储文件时将您的 Model 字段重命名为不同于 text 的名称,对我而言,这会产生误导和不确定性。

如需进一步了解FileFieldImageField,请查看official documentation

【讨论】:

  • 我收到一个错误,因为我上传的“Monthly Sale.pdf”没有存储在静态文件夹中。
  • @pete800 尝试上述解决方案。它对我有用。
猜你喜欢
  • 1970-01-01
  • 2017-10-09
  • 2018-07-28
  • 2013-12-26
  • 2023-03-25
  • 2018-10-02
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多