如何在 Django 中使用 ajax 将批量图像及其上下文上传到服务器
How to upload bulk images to server with their context using ajax in django
我一直在尝试向资产上传器添加批量图片功能。
这是图片的模型
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete = models.CASCADE)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, default = None, related_name="create_asset")
alt = models.CharField(max_length=255, default=uuid.uuid4)
title = models.CharField(max_length = 100)
width = models.IntegerField(default=0)
height = models.IntegerField(default=0)
slug = models.SlugField(max_length=200,editable = False, default=uuid.uuid4)
TWODIMENTIONAL = "2D"
THREEDIMENTIONAL = "3D"
DESIGN = "DS"
ASSET_CHOICES = (
(TWODIMENTIONAL, '2D render'),
(THREEDIMENTIONAL, '3D render'),
(DESIGN, 'Designer'),
)
asset_type = models.CharField(default=DESIGN,
max_length=2,
choices = ASSET_CHOICES,
verbose_name='Asset Type',
)
如何使用 asset_type 向此模型添加批量上传。
上传多张图片及其详细信息,如类型(复选框)和许多其他内容。
感谢您的帮助。
您是否尝试过使用这篇文章 - https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html?
settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py :
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
urlpatterns = [
# ...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
base.html:
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Photos Library - Simple is Better Than Complex{% endblock %}</title>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
{% include 'includes/header.html' %}
<div class="container">
{% block content %}
{% endblock %}
</div>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
{% block javascript %}
{% endblock %}
</body>
</html>
models.py:
class Photo(models.Model):
title = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to='photos/')
uploaded_at = models.DateTimeField(auto_now_add=True)
forms.py:
从 .models 导入照片
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('file', )
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^basic-upload/$', views.BasicUploadView.as_view(), name='basic_upload'),
]
views.py:
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from .forms import PhotoForm
from .models import Photo
class BasicUploadView(View):
def get(self, request):
photos_list = Photo.objects.all()
return render(self.request, 'photos/basic_upload/index.html', {'photos': photos_list})
def post(self, request):
form = PhotoForm(self.request.POST, self.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)
photos/basic_upload/index.html:
{% block javascript %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'photos/js/basic-upload.js' %}"></script>
{% endblock %}
photos/basic_upload/index.html:
{# 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 'photos:basic_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>
photos/js/basic-upload.js:
$(function () {
/* 1. OPEN THE FILE EXPLORER WINDOW */
$(".js-upload-photos").click(function () {
$("#fileupload").click();
});
/* 2. INITIALIZE THE FILE UPLOAD COMPONENT */
$("#fileupload").fileupload({
dataType: 'json',
done: function (e, data) { /* 3. PROCESS THE RESPONSE FROM THE SERVER */
if (data.result.is_valid) {
$("#gallery tbody").prepend(
"<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
)
}
}
});
});
我一直在尝试向资产上传器添加批量图片功能。
这是图片的模型
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete = models.CASCADE)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, default = None, related_name="create_asset")
alt = models.CharField(max_length=255, default=uuid.uuid4)
title = models.CharField(max_length = 100)
width = models.IntegerField(default=0)
height = models.IntegerField(default=0)
slug = models.SlugField(max_length=200,editable = False, default=uuid.uuid4)
TWODIMENTIONAL = "2D"
THREEDIMENTIONAL = "3D"
DESIGN = "DS"
ASSET_CHOICES = (
(TWODIMENTIONAL, '2D render'),
(THREEDIMENTIONAL, '3D render'),
(DESIGN, 'Designer'),
)
asset_type = models.CharField(default=DESIGN,
max_length=2,
choices = ASSET_CHOICES,
verbose_name='Asset Type',
)
如何使用 asset_type 向此模型添加批量上传。 上传多张图片及其详细信息,如类型(复选框)和许多其他内容。 感谢您的帮助。
您是否尝试过使用这篇文章 - https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html?
settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py :
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
urlpatterns = [
# ...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
base.html:
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Photos Library - Simple is Better Than Complex{% endblock %}</title>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
{% include 'includes/header.html' %}
<div class="container">
{% block content %}
{% endblock %}
</div>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
{% block javascript %}
{% endblock %}
</body>
</html>
models.py:
class Photo(models.Model):
title = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to='photos/')
uploaded_at = models.DateTimeField(auto_now_add=True)
forms.py: 从 .models 导入照片
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('file', )
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^basic-upload/$', views.BasicUploadView.as_view(), name='basic_upload'),
]
views.py:
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from .forms import PhotoForm
from .models import Photo
class BasicUploadView(View):
def get(self, request):
photos_list = Photo.objects.all()
return render(self.request, 'photos/basic_upload/index.html', {'photos': photos_list})
def post(self, request):
form = PhotoForm(self.request.POST, self.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)
photos/basic_upload/index.html:
{% block javascript %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static 'photos/js/basic-upload.js' %}"></script>
{% endblock %}
photos/basic_upload/index.html:
{# 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 'photos:basic_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>
photos/js/basic-upload.js:
$(function () {
/* 1. OPEN THE FILE EXPLORER WINDOW */
$(".js-upload-photos").click(function () {
$("#fileupload").click();
});
/* 2. INITIALIZE THE FILE UPLOAD COMPONENT */
$("#fileupload").fileupload({
dataType: 'json',
done: function (e, data) { /* 3. PROCESS THE RESPONSE FROM THE SERVER */
if (data.result.is_valid) {
$("#gallery tbody").prepend(
"<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
)
}
}
});
});