python - django-在Django中选择文件后预览照片
问题描述
模型.py
class Banner(models.Model):
banner_photo = models.ImageField(null=True, blank=True)
作为下面的答案,我想在 django-admin 中保存横幅图像之前预览图像选择。我是 HTml 的初学者。我如何覆盖它?
我想预览要向管理员注册的横幅图片,就像捕获的图像一样。即使我看到答案,我也不知道如何应用它。
解决方案
我最初在 Github 上发布我的答案:https ://github.com/matthewwithanm/django-imagekit/issues/444
但是,我想在这里分享它。我认为它可以帮助你和其他人。
因此,回答您的问题:是的,可以在使用 Django 管理应用程序保存之前预览您的图像。
以下是步骤:
- 在模型中定义一个自定义字段,其中包含要预览的图像(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,
})
- 在应用程序的管理配置(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',))
- 为该新字段定义一个 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 管理主题)
推荐阅读
- django - Django 表单 - 允许用户为其他用户创建组
- python - __init__() 接受 2 个位置参数,但给出了 3 个尝试使用 presence_of_element_located() 等待元素
- node.js - 当进程消耗大量内存时,NodeJs 会变慢
- php - 如何将数据库表值提取到模板文件中?
- python - 从 python 调用时,SQLite3 upsert 总是失败
- r - 使用 Rvest 抓取,POST 请求
- tcp - 为什么 TCP 接收窗口是 MSS 的倍数?
- android - 任务“:app:runCheckstyle”执行失败
- terraform - 是否可以使用 terraform 在 AWS 机密管理器中设置多用户机密轮换?
- python - 如何对作用于会话特定数据的 pytest 插件的钩子进行单元测试?