Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageField preview in crispy forms layout

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>
like image 283
Banjer Avatar asked Dec 15 '22 02:12

Banjer


1 Answers

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',
        )
like image 139
petkostas Avatar answered Jan 29 '23 12:01

petkostas