【问题标题】:how to display uploaded image on the screen using django and ajax如何使用 django 和 ajax 在屏幕上显示上传的图像
【发布时间】:2019-10-22 21:47:25
【问题描述】:

我正在尝试使用 ajax 在 django 中上传图像并将其保存在指定路径中。图片已上传并保存,但问题是它没有显示在模板中。

我在设置文件中添加了 MEDIA ROOT 和 Media URL 我创建一个模型 我在 urls 文件中创建一个路径 我在视图文件中创建一个函数 我用 html 创建一个模板并使用 ajax 和 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>

我希望看到上传的图片显示在屏幕上,但在我上传并提交表单后 src 图片保持空白。

【问题讨论】:

  • 检查我的答案,您只需对您实施的任何内容进行少量更改。

标签: ajax django image upload


【解决方案1】:

首先将这些模板行包围在 div 标签下,如下所示:

<div id="photo">
 <h2> {{ photo.title }}</h2>
     <img src="{{ photo.img.url }}" alt="{{ photo.title }}">
</div>

像这样对视图功能进行一些更改:

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)

现在在 ajax 成功函数中添加以下代码:

$("#photo").html('<h2> {{'+data.title+'}}</h2>
     <img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">')

【讨论】:

    【解决方案2】:

    你应该做几件事,,,我看到你想使用Ajax 电话,根本不需要&lt;form&gt;&lt;/form&gt;。此外,您应该例如从payload 向服务器发送csrfmiddlewaretoken 密钥(在HTTP POST 请求期间)。您应该将数据从客户端发送到服务器,服务器发回新图像的 url,您应该使用 javascript 更新 DOM

    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>
    

    蟒蛇

    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')
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 2011-08-11
      • 1970-01-01
      • 2012-09-16
      • 2021-09-08
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 2016-08-15
      相关资源
      最近更新 更多