I am creating a form that allows a user to select a image and upload it using Django and AJAX. This process works fine but the problem is that the uploaded image isn't being displayed on the screen however I did specify a div
for it.
These are the steps that I followed:
- Create a model that handle the uploaded image.
- Create a path for the function.
- Create the function that uploads the selected image.
- Create the template and AJAX function.
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)
I expect that after the user uploads the image and the image I stored in the database, the image must be displayed on the screen.
{{'+data.title+'}}