如何使用Django和AJAX显示上传的图像 [英] How to display the uploaded image using Django and AJAX

查看:60
本文介绍了如何使用Django和AJAX显示上传的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个允许用户选择图像并使用Django和AJAX上传图像的表单。这个过程工作正常,但是问题是上传的图像没有显示在屏幕上,但是我确实为其指定了 div

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.

这些是我遵循的步骤:


  • 创建一个处理上传图像的模型。

  • 创建函数的路径。

  • 创建用于上传所选图像的函数。

  • 创建模板和AJAX函数。

  • 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:

models.py:

class photo(models.Model):
    title = models.CharField(max_length=100)
    img = models.ImageField(upload_to = 'img/')

home.html:

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.

推荐答案

ImageField您必须安装枕头

For using ImageField you have to install Pillow

pip install pillow

让我们遍历您的代码并对其进行一些修改。

Let's go through your code and modify it a little.

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 我将您的视图分为两个视图。

views.py I splitted your view into two views.

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 +'}}} <中使用模板变量/ em>!
将字符串作为参数发送到HttpResponse(),在返回HttpResponse(photo)中photo是一个对象。

Do not use template variables in javascript {{'+data.title+'}} ! Send a string to HttpResponse() as an argument, in return HttpResponse(photo) photo is an object.

这篇关于如何使用Django和AJAX显示上传的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆