Question

I'd like to display the image from an ImageField. I'm using Django crispy forms. It seems I need to use the HTML layout helper, but I'm not sure how to access a template variable here.

The following renders a blank image tag:

HTML('<img src="{{ logo.url }}" />')

Am I referencing this wrong, or is there a better method in crispy forms?

Here is the full code so you can get a better idea:

forms.py

class CompanyForm(forms.Form):
    name = forms.CharField(required=False, label="Company name")
    logo = forms.ImageField(required=False, label="Logo")

    # form layout
    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.layout = Layout(
        Div(
            'name',
            HTML('<img src="{{ logo.url }}" />'),
            css_class='span4',
        ),

        FormActions(
            Submit('submit', 'Save', css_class="btn-primary pull-right"),
        )
    )

models.py

class Company(models.Model):
    name = models.CharField(max_length=100)
    logo = models.ImageField(upload_to = 'logos/', null=True)

views.py

I'm setting the initial values of the form in my view:

...
profile = Company.objects.get(name="foo")
form = CompanyForm(initial={'name': profile.name, 'logo': profile.logo, })

context = {
    'profile_form' : form,
}

return render_to_response('dashboard/company-profile.html', context_instance=RequestContext(request, context))    

company-profile.html

{% load crispy_forms_tags %}
<div class="row">
  {% crispy profile_form %}
</div>
Was it helpful?

Solution

Funny, I was just working on the same issue today on a Inline image upload formset, I ended up with this implementation:

class ImageModelForm(forms.ModelForm):

    class Meta:
        model = ImageModel

    def __init__(self, *args, **kwargs):
        super(ImageModelForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.disable_csrf = True
        self.helper.layout = Layout(
            'title',
            'description',
            'imagefile',
            HTML("""{% if form.imagefile.value %}<img class="img-responsive" src="{{ MEDIA_URL }}{{ form.imagefile.value }}">{% endif %}""", ),
            'flag_featured',
        )

OTHER TIPS

People who are seeing this from-after 2020, the this is fixed since maybe v1.10, v.1.9 or nearby. I've had same issue with v.1.8.

further to @petkostas answer, specifically on the image reload comment from @Banjer: - i also had this problem with a form and managed to solve this by introducing a conditional statement into views.py (note, context statements not included below):

if request.method == "POST":
       if form.is_valid():
          #do stuff
       return HttpResponseRedirect(reverse('your_named_url'))
elif request.method =="GET":
       return render(request, 'path/to/template.html', context)

what this does is allows the page to reload with the new content if it's updated (so you can use the form.imagefile.value attribute mentioned previously)

! this is quite a specific use case, but i hope it helps someone save a bit of time

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top