Для использования ImageField необходимо установить подушку
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 - это объект.