Gonzalo Dambra
Gonzalo Dambra

Reputation: 980

Django template: Access custom form field attributes in template

I just need one custom extra attribute in my Django form fields which is icon. I will take the example of my custom CharField.

custom_fields.py:

class ICharField(forms.CharField):
    """
    Django CharField with custom icon attr to use along with Bulma.
    """

    icon = ''

    def __init__(self, *, icon='', max_length=None, min_length=None, strip=True, empty_value='', **kwargs):
        super().__init__(**kwargs)
        self.icon = icon

forms.py:

from utils.forms import custom_fields

class SignUpForm(forms.Form):

    company_name = custom_fields.ICharField(
        icon='fas fa-envelope',
        widget=forms.TextInput(attrs={
            'class': 'input',
            'placeholder': _('Name of your company'),
            'label': _('Company'),
        })
    )

That's it, but when in the HTML I try to access to {{ field.icon }} I'm getting nothing.

the.html:

{% extends 'template_composition/main.html' %}

{% load i18n %}

{% block content %}


{% for field in form %}
<div class="field">
    <b>{{ field.label }}:</b>
    <p class="control has-icons-left">
        {{ field }}
        <span class="icon is-small is-left">
            <i class="{{ field.icon }}"></i>
        </span>
    </p>
</div>
{% endfor %}


{% endblock %}

It's obvious I'm overriding __init__ wrong, right?

Upvotes: 0

Views: 549

Answers (1)

JPG
JPG

Reputation: 88459

Use form.<field_name>.field.<field_attribute> syntax

In your case,

{{ form.company_name.field.icon }}

or by using loop,

{% for field in form %}
    {{ field.field.icon }}
{% endfor %}

Upvotes: 2

Related Questions