Reputation: 165
I am trying to apply CSS to individual {{form}} fields on my html template. I am referencing this solved question:
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.
Upvotes: 3
Views: 746
Reputation: 165
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.
Upvotes: 0
Reputation: 27503
<div class="form-group">
{% for field in form %}
<label for="id_Fullname" id="{{ field.name }}">Full Name:</label>
{{ field }}
{% endfor %}
</div>
try this
Upvotes: 2
Reputation: 59164
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>
Upvotes: 1