prelude:
Here\'s the simpliest way to display an ImageField. Lets assume I have 10 fields in my form and I don\'t wanna iterate over all of them in
Let me improve this interesting question. I suggest to combine image input and image preview. Subclass FileInput widget and override render to concatenate additional html to display preview image and default input image html.
from django.utils.safestring import mark_safe
from django import forms
class ImagePreviewWidget(forms.widgets.FileInput):
def render(self, name, value, attrs=None, **kwargs):
input_html = super().render(name, value, attrs=None, **kwargs)
img_html = mark_safe(f'
')
return f'{input_html}{img_html}'
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = '__all__'
photo = forms.ImageField(widget=ImagePreviewWidget,)