如何使用Django和AJAX显示上传的图片
How to display the uploaded image using Django and AJAX
我正在创建一个允许用户 select 图片并使用 Django 和 AJAX 上传的表单。这个过程工作正常,但问题是上传的图像没有显示在屏幕上,但是我确实为它指定了 div
。
这些是我遵循的步骤:
- 创建处理上传图像的模型。
- 为函数创建路径。
- 创建上传 selected 图片的函数。
- 创建模板和AJAX函数。
models.py:
class photo(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to = 'img/')
home.html:
<form method="POST" id="ajax" enctype="multipart/form-data">
{% csrf_token %}
Img:
<br />
<input type="file" name="img">
<br />
<br />
<button id="submit" type="submit">Add</button>
</form>
<h1> test </h1>
<div id="photo">
<h2> {{ photo.title }}</h2>
<img src="{{ photo.img.url }}" alt="{{ photo.title }}">
</div>
$('#ajax').submit(function(e) {
e.preventDefault();
var data = new FormData($('#ajax').get(0));
console.log(data)
$.ajax({
url: '/upload/',
type: 'POST',
data: data,
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
// alert('gd job');
$("#photo").html('<h2> {{'+data.title+'}}</h2> <img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">')
}
});
return false;
});
views.py:
def upload(request):
if request.method == 'POST':
if request.is_ajax():
image = request.FILES.get('img')
uploaded_image = photo(img = image)
uploaded_image.save()
photo=photo.objects.first()
# return render(request, 'home2.html')
return HttpResponse(photo)
我期望用户上传图片和我存入数据库的图片后,一定要在屏幕上显示图片
要使用 ImageField,您必须安装 Pillow
pip install pillow
让我们检查一下您的代码并稍微修改一下。
models.py
from django.db import models
# Create your models here.
class Photo(models.Model):
title = models.CharField(max_length=100) # this field does not use in your project
img = models.ImageField(upload_to='img/')
views.py 我把你的观点分成了两个观点。
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
import json
# Create your views here.
def home(request):
return render(request, __package__+'/home.html', {})
def upload(request):
if request.method == 'POST':
if request.is_ajax():
image = request.FILES.get('img')
uploaded_image = Photo(img=image)
uploaded_image.save()
response_data = {
'url': uploaded_image.img.url,
}
return HttpResponse(json.dumps(response_data))
urls.py
from django.urls import path
from .views import *
from django.conf.urls.static import static
from django.conf import settings
app_name = __package__
urlpatterns = [
path('upload/', upload, name='upload'),
path('', home, name='home'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_URL = '/img/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'img')
home.html
{% load static %}
<html>
<head>
<script src="{% static 'photo/jquery-3.4.1.js' %}"></script>
<script>
$(document).ready(function() {
$('#ajax').submit(function(e) {
e.preventDefault(); // disables submit's default action
var data = new FormData($('#ajax').get(0));
console.log(data);
$.ajax({
url: '/upload/',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
data = JSON.parse(data); // converts string of json to object
$('#photo').html('<img src="'+data.url+ '" />');
// <h2>title</h2> You do not use 'title' in your project !!
// alt=title see previous comment
}
});
return false;
});
});
</script>
</head>
<body>
<form method="POST" id="ajax">
{% csrf_token %}
Img:
<br />
<input type="file" name="img" />
<br />
<br />
<button id="submit" type="submit">Add</button>
</form>
<h1> test </h1>
<div id="photo"></div>
</body>
</html>
不要在 javascript {{'+data.title+'}} 中使用模板变量!
将字符串作为参数发送到 HttpResponse(),在 return HttpResponse(photo) photo 是一个对象。
对于多个表单:
views.py
def home(request):
context = {
'range': range(3),
}
return render(request, __package__+'/home.html', context)
home.html
{% load staticfiles %}
<html>
<head>
<script src="{% static 'photo/jquery-3.4.1.js' %}"></script>
<script>
$(document).ready(function() {
$('.ajax').each(function () {
$(this).submit(function (e) {
e.preventDefault(); // disables submit's default action
var data = new FormData($(this).get(0));
var imageForm = $(this);
$.ajax({
url: '/upload/',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
data = JSON.parse(data); // converts string of json to object
imageForm.parent().find('.photo').html('<img src="'+data.url+ '" />');
console.log(imageForm);
}
});
return false;
});
});
});
</script>
</head>
<body>
{% for i in range %}
<div style="border: 1px solid black">
<form method="POST" class="ajax">
{% csrf_token %}
<div class="upload-label">Img-{{ i }}:</div>
<input type="file" name="img" />
<br />
<br />
<button class="submit" type="submit">Add</button>
</form>
<div class="image-label"> Image: </div>
<div class="photo">No image yet</div>
</div>
{% endfor %}
</body>
</html>
我正在创建一个允许用户 select 图片并使用 Django 和 AJAX 上传的表单。这个过程工作正常,但问题是上传的图像没有显示在屏幕上,但是我确实为它指定了 div
。
这些是我遵循的步骤:
- 创建处理上传图像的模型。
- 为函数创建路径。
- 创建上传 selected 图片的函数。
- 创建模板和AJAX函数。
models.py:
class photo(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to = 'img/')
home.html:
<form method="POST" id="ajax" enctype="multipart/form-data">
{% csrf_token %}
Img:
<br />
<input type="file" name="img">
<br />
<br />
<button id="submit" type="submit">Add</button>
</form>
<h1> test </h1>
<div id="photo">
<h2> {{ photo.title }}</h2>
<img src="{{ photo.img.url }}" alt="{{ photo.title }}">
</div>
$('#ajax').submit(function(e) {
e.preventDefault();
var data = new FormData($('#ajax').get(0));
console.log(data)
$.ajax({
url: '/upload/',
type: 'POST',
data: data,
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
// alert('gd job');
$("#photo").html('<h2> {{'+data.title+'}}</h2> <img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">')
}
});
return false;
});
views.py:
def upload(request):
if request.method == 'POST':
if request.is_ajax():
image = request.FILES.get('img')
uploaded_image = photo(img = image)
uploaded_image.save()
photo=photo.objects.first()
# return render(request, 'home2.html')
return HttpResponse(photo)
我期望用户上传图片和我存入数据库的图片后,一定要在屏幕上显示图片
要使用 ImageField,您必须安装 Pillow
pip install pillow
让我们检查一下您的代码并稍微修改一下。
models.py
from django.db import models
# Create your models here.
class Photo(models.Model):
title = models.CharField(max_length=100) # this field does not use in your project
img = models.ImageField(upload_to='img/')
views.py 我把你的观点分成了两个观点。
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
import json
# Create your views here.
def home(request):
return render(request, __package__+'/home.html', {})
def upload(request):
if request.method == 'POST':
if request.is_ajax():
image = request.FILES.get('img')
uploaded_image = Photo(img=image)
uploaded_image.save()
response_data = {
'url': uploaded_image.img.url,
}
return HttpResponse(json.dumps(response_data))
urls.py
from django.urls import path
from .views import *
from django.conf.urls.static import static
from django.conf import settings
app_name = __package__
urlpatterns = [
path('upload/', upload, name='upload'),
path('', home, name='home'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_URL = '/img/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'img')
home.html
{% load static %}
<html>
<head>
<script src="{% static 'photo/jquery-3.4.1.js' %}"></script>
<script>
$(document).ready(function() {
$('#ajax').submit(function(e) {
e.preventDefault(); // disables submit's default action
var data = new FormData($('#ajax').get(0));
console.log(data);
$.ajax({
url: '/upload/',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
data = JSON.parse(data); // converts string of json to object
$('#photo').html('<img src="'+data.url+ '" />');
// <h2>title</h2> You do not use 'title' in your project !!
// alt=title see previous comment
}
});
return false;
});
});
</script>
</head>
<body>
<form method="POST" id="ajax">
{% csrf_token %}
Img:
<br />
<input type="file" name="img" />
<br />
<br />
<button id="submit" type="submit">Add</button>
</form>
<h1> test </h1>
<div id="photo"></div>
</body>
</html>
不要在 javascript {{'+data.title+'}} 中使用模板变量! 将字符串作为参数发送到 HttpResponse(),在 return HttpResponse(photo) photo 是一个对象。
对于多个表单:
views.py
def home(request):
context = {
'range': range(3),
}
return render(request, __package__+'/home.html', context)
home.html
{% load staticfiles %}
<html>
<head>
<script src="{% static 'photo/jquery-3.4.1.js' %}"></script>
<script>
$(document).ready(function() {
$('.ajax').each(function () {
$(this).submit(function (e) {
e.preventDefault(); // disables submit's default action
var data = new FormData($(this).get(0));
var imageForm = $(this);
$.ajax({
url: '/upload/',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
data = JSON.parse(data); // converts string of json to object
imageForm.parent().find('.photo').html('<img src="'+data.url+ '" />');
console.log(imageForm);
}
});
return false;
});
});
});
</script>
</head>
<body>
{% for i in range %}
<div style="border: 1px solid black">
<form method="POST" class="ajax">
{% csrf_token %}
<div class="upload-label">Img-{{ i }}:</div>
<input type="file" name="img" />
<br />
<br />
<button class="submit" type="submit">Add</button>
</form>
<div class="image-label"> Image: </div>
<div class="photo">No image yet</div>
</div>
{% endfor %}
</body>
</html>