【问题标题】:Django - Show a list of file in a template, taking the files from the MEDIA folder of the serverDjango - 在模板中显示文件列表,从服务器的 MEDIA 文件夹中获取文件
【发布时间】:2019-08-25 20:09:09
【问题描述】:

我想在 Django 应用程序的前端以表单的形式显示来自我服务器上 MEDIA_ROOT 的文件列表。

低于我想要完成的目标:

下面是我的实际代码。我只显示受问题影响的类、函数和文件。如果缺少某些内容,您会在问题的最后找到完整项目的链接。

views.py(我有两个函数,因为我尝试了两种方法)

class SelectPredFileView(TemplateView):
    """
    This view is used to select a file from the list of files in the server.
    """
    model = FileModel
    fields = ['file']
    template_name = 'select_file_predictions.html'
    success_url = '/predict_success/'
    files = os.listdir(settings.MEDIA_ROOT)

    def my_view(request):
        my_objects = get_list_or_404(FileModel, published=True)
        return my_objects

    # TODO: file list not displayed in the HTML, fix
    def getfilelist(self, request):
        filepath = settings.MEDIA_ROOT
        file_list = os.listdir(filepath)
        return render_to_response('templates/select_file_predictions.html', {'file_list': file_list})

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")

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

models.py

from django.db import models
from django.conf import settings


class FileModel(models.Model):
    file = models.FileField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    path = models.FilePathField(path=settings.MEDIA_ROOT, default=settings.MEDIA_ROOT)

urls.py

from django.contrib import admin
from django.conf import settings
from django.urls import path, re_path
from django.views.static import serve
from django.conf.urls import url, include
from django.conf.urls.static import static

from App.views import UploadView, UploadSuccessView, IndexView, SelectPredFileView, PredictionsSuccessView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^App/', include('App.urls'), name="App"),
    url('index/', IndexView.as_view(), name='index'),

    # Urls to upload the file and confirm the upload
    url('fileupload/', UploadView.as_view(), name='upload_file'),
    url('upload_success/', UploadSuccessView.as_view(), name='upload_success'),

    # Urls to select a file for the predictions
    url('fileselect/', SelectPredFileView.as_view(), name='file_select'),
    url('predict_success/', PredictionsSuccessView.as_view(), name='pred_success'),
]

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

if settings.DEBUG:

    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
        re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
    ] + urlpatterns

select_file_predictions.html

{% extends "index.html" %}

{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        {% for file in my_objects %}
          <input type="checkbox" name={ file } value="{ file }"><br>
        {% endfor %}
        <button type="submit" class="btn btn-primary">Upload file</button>
    </form>
{% endblock %}

ISSUE:该文件未显示在 html 模板中。

如果你想深入了解,应用程序的完整代码在这里:https://github.com/marcogdepinto/Django-Emotion-Classification-Ravdess-API

我检查但无法解决此问题的问题:

1) Iterate through a static image folder in django

2) Django - Render a List of File Names to Template

3)List directory file contents in a Django template

【问题讨论】:

  • 您有什么特别的问题吗?
  • 抱歉,刚刚编辑了问题并添加了一个屏幕:文件列表未显示在 HTML 中。

标签: python django


【解决方案1】:

我会这样做:

views.py

from os import listdir
from os.path import isfile, join

import settings
from django.views.generic.base import TemplateView


class MyFilesView(TemplateView):

    template_name = "select_file_predictions.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)        

        # List of files in your MEDIA_ROOT
        media_path = settings.MEDIA_ROOT
        myfiles = [f for f in listdir(media_path) if isfile(join(media_path, f))]
        context['myfiles'] = myfiles

        return context

select_file_predictions.html

{% extends "index.html" %}

{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        {% for myfile in myfiles %}
          <input type="checkbox" name={{ myfile }} value="{{ myfile }}"><br>
        {% endfor %}
        <button type="submit" class="btn btn-primary">Upload file</button>
    </form>
{% endblock %}

【讨论】:

  • 谢谢洛伦佐,它成功了!我只在模板中做了一个小改动来显示文件名 {{ myfile }}
  • 不客气,马可! (felice di esserti stato utile :-))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 2013-03-20
相关资源
最近更新 更多