3

I am trying to apply CSS to individual {{form}} fields on my html template. I am referencing this solved question:

CSS styling in Django forms`

using the answer I created my forms.py page as follows:

from django import forms
from .models import ContactInfo


class ContactForm(forms.ModelForm):
# class meta brings in the fields from models
class Meta:
    model = ContactInfo

    # grab the fields from models ContactInfo class
    fields = ('Fullname')

    # specify which bootstrap class each html widget should take
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['Fullname'].widget.attrs.update({'class': 'form-control'})

html using {{form}} elements:

<div class="form-group">
  <label for="id_Fullname">Full Name:</label>
  {{form.Fullname}}
</div>

The working html w/o usage of {{form}}:

<div class="form-group"> <label for="fullname">Full Name:</label> <input type="text" class="form-control" id="fullname"> </div>

How do I get the "label" tag to point to the id inside {{form.Fullname}}. My guess is it is not doing that right now hence it doesn't apply the css. That or the class i specified in the widgets in the forms.py is not working how I want it to.

Community
  • 1
  • 1
Darryl Lobo
  • 155
  • 3
  • 18

3 Answers3

2
<div class="form-group">
{% for field in form %}
  <label for="id_Fullname" id="{{ field.name }}">Full Name:</label>
  {{ field }}
{% endfor %}
</div>

try this

Exprator
  • 26,992
  • 6
  • 47
  • 59
  • Does not work. I must be missing something from the other solutions to this problem I see on stack overflow. Will try to do this again from scratch. – Darryl Lobo May 22 '17 at 14:42
  • solved! my def __init__ function was inside the Class Meta instead of Class ContactForm. Nothing wrong with the solutions suggested it was an error in placing the def__init__ – Darryl Lobo May 22 '17 at 14:59
1

You can use the id_for_label property of field:

Use this property to render the ID of this field. For example, if you are manually constructing a <label> in your template.

<div class="form-group">
  <label for="{{ form.Fullname.id_for_label }}">Full Name:</label>
  {{ form.Fullname }}
</div>
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • I tried inputing what you suggested. Same deal. Not sure if this means anything. My IDE( jetbrains/pycharm) highlights {{ form.Fullname.id_for_label }} in red mentioning unresolved id by inspecting the xml. I feel like the form.Fullname does not contain an auto created id from the ModelForm class. Will keep reading your link. – Darryl Lobo May 22 '17 at 04:35
0

This was an error of placing the def init function inside Class Meta: instead of Class ContactInfo. I had not realized I had indented it improperly.

Darryl Lobo
  • 155
  • 3
  • 18