Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access django form field name in template

I've got a modelform that I would like to iterate through the form fields in the template but at the same time, when I encounter certain fields, to conditionally render extra html. Currently I am pulling the field name from field.html_name but I am not sure if that is the best way (it feels hackish somehow, like I should be using a getattr() filter or something...).

{% for field in form %}
<div class="form-group">

    {{ field }}

    {% if field.html_name == "location" %}
      <!-- CUSTOM HTML HERE -->
    {% endif %}

</div>   
{% endfor %}
like image 918
cowbert Avatar asked Aug 18 '16 05:08

cowbert


People also ask

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is field ID in Django?

each form field has an ID attribute set to id_<field-name> , which is referenced by the accompanying label tag. This is important in ensuring that forms are accessible to assistive technology such as screen reader software. You can also customize the way in which labels and ids are generated.

How do forms get rendered using Django templates?

Form data sent back to a Django website is processed by a view, generally the same view which published the form. This allows us to reuse some of the same logic. If we arrive at this view with a GET request, it will create an empty form instance and place it in the template context to be rendered.

What is form Cleaned_data in Django?

form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).


3 Answers

I have the same situation if I don't misunderstand your mean. My solution is field.name. Code sample:

{% if field.name == 'password' %}
   <input type="password" name="password" class="form-control" placeholder="{% trans 'Enter your password' %}">
{% else %}
   <input type="email" name="email" class="form-control" placeholder="{% trans 'Enter your email address' %}">
{% endif %}
like image 186
Nguyễn Thái Sơn Avatar answered Oct 04 '22 22:10

Nguyễn Thái Sơn


I don't know how you mean, but you can try this

{% for field in form %}
   {{ field }}
   {% if field.label == 'Location' %}
      <h1>Hi</h1>
   {% endif %}
{% endfor %}

Whereas, you would have set label in forms.py as

location = forms.CharField(widget=forms.TextInput(
        attrs={'class': 'yourclass', 'placeholder': 'Enter your location',
               }), label=u'Location', max_length=100, required=True)
like image 43
Temi 'Topsy' Bello Avatar answered Oct 04 '22 20:10

Temi 'Topsy' Bello


Have you considered using a widget or creating your own custom widget? https://docs.djangoproject.com/en/1.10/ref/forms/widgets/

E.g.: for adding just a css class or similiar to the existing input use the attrs argument

class MyForm(forms.Form):
     ...
     location = forms.CharField(
          ...,
          widget=Input(attrs={'class': 'location', 'style': 'background: red'}),
     )
     ...

Or creating a complete custom widget (take a look at how Input is implemented)

class LocationFieldWidget(Widget):
    def render(self, name, value, attrs=None):
        return mark_safe('custom html')

and then the form can be rendered in the template simply by

 {{ form }}
like image 29
zsepi Avatar answered Oct 04 '22 22:10

zsepi