欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 上传图片的预览

上传图片的预览

2025/2/22 2:06:55 来源:https://blog.csdn.net/weixin_47021806/article/details/144548572  浏览:    关键词:上传图片的预览

解决:在上传图片时,1显示已有的图片 2显示准备替换的图片


![[Pasted image 20241218061930.png]]


在这里插入图片描述

在这个案例中可以预览到 【已有与准备替换】 2张图片

具体流程

1创建一个共享组件

与manage.py同级别路径的文件

manage.py
custom_widgets.py

在这里插入图片描述

# custom_widgets.py
from django import forms
from django.utils.safestring import mark_safe
from django.template.loader import render_to_stringclass CustomClearableFileInput(forms.ClearableFileInput):template_name = 'custom_clearable_file_input.html'def render(self, name, value, attrs=None, renderer=None):context = self.get_context(name, value, attrs)return mark_safe(render_to_string(self.template_name, context))

2 在templates中创建这个组件用到的html文件

templates/custom_clearable_file_input.html
{% if widget.is_initial %}<div class="current-image"><p>当前图片:</p><img src="{{ widget.value.url }}" style="max-width: 200px; max-height: 200px;" alt="现有使用中的图片" />{% if not widget.is_required %}<span class="clearable-file-input"><input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"><label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label></span>{% endif %}</div>
{% endif %}
<div class="new-image"><p>上传新图片:</p><input type="file" name="{{ widget.name }}" accept="image/*" id="{{ widget.attrs.id }}">&l

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词