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
I can't comment yet, thus I need to add this via an Answer. All credits to deathangel908 for this handy solution.
I'm using Django 2.1 and was struck with TypeError: render() got an unexpected keyword argument 'renderer'
error when trying the accepted answer. Solution to this problem can be found here: https://stackoverflow.com/a/52039655/8002464
In short, the solution must be slightly changed for Django 2.1 and upwards and include renderer=None
. Fully updated solution:
from string import Template
from django.utils.safestring import mark_safe
from django.forms ImageField
class PictureWidget(forms.widgets.Widget):
def render(self, name, value, attrs=None, renderer=None):
html = Template("""
""")
return mark_safe(html.substitute(link=value))
class UserProfileForm(forms.ModelForm):
photo = ImageField(widget=PictureWidget)
Btw. a quick small improvement, at least for my use-case was to add the media url. This way the images were actually shown instead of being lost in wrong urls. But this might only be because of how I set up my urls.
from django.conf import settings
[...]
html = Template("""
""")
return mark_safe(html.substitute(media=settings.MEDIA_URL, link=value))