Display initial form.FileField as img tag in template

时间:2015-06-26 09:58:16

标签: django django-forms django-templates

My form class:

class MyForm(forms.Form):
    image = forms.ImageField()

in the view (GET case) I instance the form (then I pass it to the template ctx):

form = MyForm(initial={'image':my_model_obj.image})

now in template i wanto to display the image as:

<img src="{{form.image.url}}">

but that doesn't work, the src just stay blank.

as a workaround I did that in the view:

form = MyForm()
form.image_display = my_model_obj.image

and in the template:

<img src="{{form.image_display.url}}">

Is that the way to do it? (I know I can pass the image as a context variable but meh..)

Thank you in advance

1 个答案:

答案 0 :(得分:0)

我没有测试过这个:D只是在docs中找到了

from django.core.files.uploadedfile import SimpleUploadedFile

file_data = {'image': SimpleUploadedFile(my_model_obj.image.name.split('/')[-1], my_model_obj.image.file)}
form = MyForm(file_data)

https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form