0

How to add a class to django form label?

I have <label for="id_first_name">First name:</label> when I use {{ form.first_name.label_tag }}

I want to add class="col-sm-4 control-label" with label.How can I do that?

1 Answer 1

1

You can use form init method to call class

class YourForm(forms.Form)
def __init__(self, *args, **kwargs):
    super(YourForm, self).__init__(*args, **kwargs)
    self.fields['field_name'].widget.attrs['class'] = 'your_class'
Sign up to request clarification or add additional context in comments.

5 Comments

I tried def __init__(self, *args, **kwargs): super(SubAdminForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' def __init__(self, *args, **kwargs): super(SubAdminForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' I think this is used for adding class for input fields, I want to add a class for <label></label>
you can do same thing for label too. instead of fields use label thats all
if you want to add calss in your label in your template then call your label like {{form.field.label}}
sorry i used like {{ form.first_name.label_tag }} but i get an output like <label for="id_first_name">First name:</label> i want to add class="col-sm-4 control-label" with label
@VineethaKD: AttributeError: 'Form' object has no attribute 'labels'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.