首页 > 解决方案 > django-在Django中选择文件后预览照片

问题描述

模型.py

class Banner(models.Model):
    banner_photo = models.ImageField(null=True, blank=True)

作为下面的答案,我想在 django-admin 中保存横幅图像之前预览图像选择。我是 HTml 的初学者。我如何覆盖它?

我想预览要向管理员注册的横幅图片,就像捕获的图像一样。即使我看到答案,我也不知道如何应用它。

onchange 文件输入更改 img src 并更改图像颜色 在此处输入图像描述

标签: pythondjango

解决方案


我最初在 Github 上发布我的答案:https ://github.com/matthewwithanm/django-imagekit/issues/444

但是,我想在这里分享它。我认为它可以帮助你和其他人。

因此,回答您的问题:是的,可以在使用 Django 管理应用程序保存之前预览您的图像。

以下是步骤:

  1. 在模型中定义一个自定义字段,其中包含要预览的图像(models.py)
from django.contrib.admin.decorators import display
from django.db.models import Model
from django.db.models.fields.files import ImageField
from django.template.loader import get_template


class MyModel(Model):
    my_image_field = ImageField()

    # This is our new field. It renders a preview of the image before and post save.
    @display(description='Preview')
    def my_image_thumbnail(self):
        return get_template('my_image_thumbnail_template.html').render({
            'field_name': 'my_image_field',
            'src': self.my_image_field.url if self.my_image_field else None,
        })
  1. 在应用程序的管理配置(admin.py) 中使这个新字段可用:
from django.contrib import admin

from .models import MyModel

admin.site.register(MyModel, fields=('my_image_thumbnail', 'image'), readonly_fields=('my_image_thumbnail',))
  1. 为该新字段定义一个 html 模板(my_image_thumbnail_template.html)
<!-- This template is reusable, so you don't need to create one for each field that you want a thumbnail -->

<img
  <!--
    If there's no image, for example, when we are adding a new instance,
    we can fill the empty image preview with a placeholder image.
    If want to get this placeholder image URL from your static files,
    must load their URL in the `MyModel.my_image_thumbnail` method.
    Here is a thread that shows how to do it: https://stackoverflow.com/questions/11721818
  -->
  src="{% if src %}{{ src }}{% else %}http://atrilco.com/wp-content/uploads/2017/11/ef3-placeholder-image.jpg{% endif %}"
  id="image-thumbnail-{{ field_name }}"
>

<script>
  // Vainilla javascript  (Babel defaults, not ie 11, not ie_mob 11)

  // This function adds an event listener over the input image field (`my_field_image`).
  // If the user edits that field, the preview image will be updated.
  function changeThumbnail() {
    const fieldName = "{{ field_name }}";
    document
      .getElementById(`id_${fieldName}`)
      .addEventListener("change", function (e) {
        const reader = new FileReader();
        reader.onload = function (e) {
          document.getElementById(`image-thumbnail-${fieldName}`).src = e.target.result;
        };
        reader.readAsDataURL(this.files[0]);
      });
  }

  // This function executes a callback when the document is ready.
  // https://stackoverflow.com/questions/9899372
  //
  // Is this required?
  // No, but, in most cases, the image preview is rendered above the input field,
  // as we do in the `admin.py` module.
  // In that case, need to wait for the document to be ready before adding the
  // event listener defined in `changeThumbnail`.
  function docReady(fn) {
    if (document.readyState === "complete" || document.readyState === "interactive") {
      setTimeout(fn, 1);
    } else {
      document.addEventListener("DOMContentLoaded", fn);
    }
  }
   docReady(changeThumbnail);
</script>

结果

没有图像的新模型实例

没有图像的新实例

带有图像的新模型实例

带有图像的新实例

对于好奇:我使用 django-jazzmin(自定义 Django 管理主题)


推荐阅读