Я хочу загружать файлы на мой сайт в динамическом пути и перечислять их все, но я не знаю, как вызывать файлы, потому что они находятся в динамическом пути.Проблема в том, что я позволяю пустому полю файла, поэтому, когда я использую «objects.all ()», в нем также будет указано пустое значение, которое я не хочу, чтобы оно отображалось.
from django.db import models
from django.utils import timezone
import datetime
# Create your models here.
def upload_to(instance, filename):
return 'uploads/{id}/{fn}'.format(id=instance.pk,fn=filename)
class Chemkin(models.Model):
mechanism_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True)
thermo_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True)
transport_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True)
surface_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True)
timestamps = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return 'upload_to'
def save(self, *args, **kwargs):
"""
The folder used to upload the files to, depends on the id (primary key)
of the Chemkin object. If that is newly created and not yet saved, it
doesn't have an id yet. So to save the Chemkin object and all its files,
you need to save the Chemkin object first with no files if it has no id,
before then saving it again with the files re-attached.
This solution is based on john.don83 answer here
/7052167/zagruzka-administrativnogo-faila-django-s-identifikatorom-tekuschei-modeli
"""
if self.id is None:
files_saved_for_later = []
for f in self.__class__._meta.get_fields():
if isinstance(f, models.FileField):
files_saved_for_later.append((f.name, getattr(self, f.name)))
setattr(self, f.name, None)
# Save the model once witout files to create an id
super(self.__class__, self).save(*args, **kwargs)
for name, val in files_saved_for_later:
setattr(self, name, val)
# Save the model, with all the files
super(self.__class__, self).save(*args, **kwargs)
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import Chemkinupload
from .models import Chemkin
from django.http import HttpResponseRedirect
from django.core.files.storage import FileSystemStorage
# Create your views here.
class Home(TemplateView):
template_name = 'home.html'
#pass
def upload(request):
# if request.method == 'POST':
# uploaded_file = request.FILES['document']
# if uploaded_file.endwith('.inp', '.dat', '.txt', 'xls', 'xml'):
# fs = FileSystemStorage()
# file_name = fs.save(upload_file.name, uploaded_file)
# context['url'] = fs.url(file_name)
# else:
# return render(request, 'upload.html', {})
if request.method == 'POST':
form = Chemkinupload(request.POST, request.FILES)
if form.is_valid:
form.save()
return HttpResponseRedirect('/list/')
else:
form = Chemkinupload()
return render(request, 'upload.html', {
'form': form
})
def upload_list(request):
uploaded_files = Chemkin.objects.all()
return render(request, 'list.html', {
'uploaded_files': uploaded_files
})
def ace(request):
return render(request, 'ace.html', {})
{% extends 'base.html' %}
{% block content %}
<table>
<tr>
<th>File name</th>
</tr>
<tbody>
{% for file in uploaded_files %}
<tr>
<td> <a href="{{MEDIA_URL}}{{ file.mechanism_file }}">{{ file.uploaded_file.name }}</a> <button>edit</button></td>
<td><button>Download</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
, пожалуйста, помогите мне, как получить имя / путь к загруженным файлам в списке?