Reputation: 45
I want to create Django form with label and input. i successfully add css class to input field but i don't know how to add css class to its input label
form.py
from django import forms
from .models import TestForm
class addForm(forms.ModelForm):
class Meta:
model = TestForm
fields = ('name', 'address', 'mobile')
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control'}),
'address': forms.Textarea(attrs={'class': 'form-control'}),
'mobile': forms.TextInput(attrs={'class': 'form-control'})
}
Model.py
from django.db import models
# Create your models here.
class TestForm(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=200)
mobile = models.CharField(max_length=20)
addform.html
{%extends 'base.html'%}
{%block main%}
<div class="row clearfix" xmlns="http://www.w3.org/1999/html">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="body">
<h2 class="card-inside-title">Floating Label Examples</h2>
<div class="row clearfix">
<div class="col-sm-12">
<div class="form-group form-float">
<div class="form-line">
<form method="post"/>
{% csrf_token%}
{{form.as_p}}
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{%endblock%}
Current Output:-
<label for="id_name">Name:</label>
<input type="text" name="name" class="form-control" maxlength="50" required id="id_name">
Required Output :-
<input type="text" class="form-control">
<label class="form-label">Username</label>
Did not get class in label, guys please help me how can i get class in label
Upvotes: 0
Views: 1927
Reputation: 642
You don’t have to let Django unpack the form’s fields; you can do it manually if you like. Each field is available as an attribute of the form using {{ form.name_of_field }}
, and in a Django template, will be rendered appropriately. As you unpack the form with form.as_p
you can add your css classes like :
<p><label class="my-classes" for="{{ form.name.id_for_label }}">Name:</label>
{{ form.name }}</p>
<p><label class="my-classes" for="{{ form.address.id_for_label }}">Address:</label>
{{ form.address}}</p>
<p><label class="my-classes" for="{{ form.mobile.id_for_label }}">Mobile:</label>
{{ form.mobile}}</p>
Upvotes: 1