我想为Django中的应用程序实现动态多图像上传。我知道Django没有对此的任何内置支持,必须使用外部库。
但是我得到的结果与预期的结果相去甚远。
从settings.py开始
import os
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
models.py
class Images(models.Model):
file = models.FileField(upload_to='profile_images')
category = models.CharField(max_length=20, blank=False)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.category
forms.py
class ImagesForm(forms.ModelForm):
class Meta:
model = Images
fields = ['file',]
upload.html
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form id="category_form" method="post" action="/rango/upload/" enctype="multipart/form-data">
{% csrf_token %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/vendor/jquery.ui.widget.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.iframe-transport.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.fileupload.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.22.0/js/jquery.fileupload.js"></script>
{# 1. BUTTON TO TRIGGER THE ACTION #}
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
{# 2. FILE INPUT TO BE USED BY THE PLUG-IN #}
<input id="fileupload" type="file" name="file" multiple
style="display: none;"
data-url="{% url 'upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
{# 3. TABLE TO DISPLAY THE UPLOADED PHOTOS #}
<table id="gallery" class="table table-bordered">
<thead>
<tr>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for photo in photos %}
<tr>
<td><a href="{{ photo.file.url }}">{{ photo.file.name }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="modal fade" id="modal-progress" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
views.py
def upload(request):
photos_list = Images.objects.all()
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)
return render(request, 'rango/upload.html', {'photos': photos_list},)
我在/upload/
页面上获得的输出是
如您所见,只有文本显示在“上传”按钮和上传进度栏上,并且实际上不起作用。
我的猜测是未包含jQuery库或/和JavaScript代码无法正常工作。我是后端工程师,所以请原谅这可能是关于前端的愚蠢问题。
如果有人对代码的特殊性有所帮助,请多谢。