I have a model and a form (forms.ModelForm) in which I have an ImageField. The model resembles:
class Business(models.Model):
business_name = models.Char
This is my version of an imageInput that shows the image and doesn't allow for clearing the image
Just have to specify in the form class that the field has widget=NonClearableImageInput()
from django.forms.widgets import FileInput
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
class NonClearableImageInput(FileInput):
def render(self, name, value, attrs=None):
template = '%(input)s'
data = {'input': None, 'url': None}
data['input'] = super(NonClearableImageInput, self).render(name, value, attrs)
if hasattr(value, 'url'):
data['url'] = conditional_escape(value.url)
template = '%(input)s
'
return mark_safe(template % data)