问题
I'm trying to upload image in django using ajax and to save it in a specified path. the image is uploaded and saved but the problem is that it doesn't display in the template.
i added to the settings file the MEDIA ROOT & Media URL i create a model i create a path in the urls file i create a function in the views file i create a template with html and use the ajax and jquery.
models.py
class photo(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to = 'img/')
urls.py
from django.contrib import admin
from django.urls import path, include
from.views import *
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home2),
path('upload/', upload),
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from testapp.models import *
import json as simplejson
def upload(request):
if request.method == 'POST':
if request.is_ajax():
image = request.FILES.get('img')
uploaded_image = photo(img = image)
uploaded_image.save()
return render(request, 'home2.html')
home2.html
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
<script>
function upload(event) {
event.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('success');
}
});
return false;
}
</script>
</head>
<body>
<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>
<h2> {{ photo.title }}</h2>
<img src="{{ photo.img.url }}" alt="{{ photo.title }}">
</body>
</html>
i expect to see the uploaded image displayed on the screen but the src image stay empty after i upload and submit the form.
回答1:
First surround these lines of template under div tag like this:
<div id="photo">
<h2> {{ photo.title }}</h2>
<img src="{{ photo.img.url }}" alt="{{ photo.title }}">
</div>
Do few changes in view function like this:
from django.http import HttpResponse
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()# This will give last inserted photo
return HttpResponse(photo)
Now in the ajax success function add this code:
$("#photo").html('<h2> {{'+data.title+'}}</h2>
<img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">')
回答2:
You should do several things,,, As i see you want to use Ajax call, not neccessary to have <form></form> at all. Also, you should send csrfmiddlewaretoken key to the server (During HTTP POST request) from payload for example. You should send data from client to server, server sends back url of new image and you should update DOM using javascript.
html
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
</head>
<body>
Img:
<br />
<input type="file" name="img" id="img">
<br />
<br />
<button id="submit" type="submit">Add</button>
<div id="img_div">
</div>
<script>
$('#submit').click(function() {
event.preventDefault();
var formData = new FormData();
$img = $('#img')[0].files[0];
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
formData.append('image', $img);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data) {
$('#img_div').append('<img src="'+data['image_url']+'" />')
}
});
return false;
});
</script>
</body>
</html>
python
from django.shortcuts import render,redirect
from django.http import HttpResponse, JsonResponse
from testapp.models import *
import json as simplejson
def upload(request):
if request.method == 'POST':
if request.is_ajax():
image = request.FILES.get('image')
uploaded_image = photo.objects.create(img=image)
return JsonResponse({'image_url': uploaded_image.img.url})
return render(request, 'home2.html')
Hope, it helps you.
来源:https://stackoverflow.com/questions/56493419/how-to-display-uploaded-image-on-the-screen-using-django-and-ajax