How to style Django Forms with Bootstrap

Though we can use third-party packages like Django-Crispy forms to style forms in django with ease but still it’s sometimes required to style django generated forms all by yourself, here we will see how to do that. the form will be able to show errors also.

in this example,

this is the template file with the form.

<!DOCTYPE html>
<link href="" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<h1>Example Form</h1>
<div style="width:30%">
<form action="">
{% for error in form.non_field_errors %}
<div class="form-group has-errors text-danger small">
{% endfor %}
{% for field in form %}
<div class="form-group has-errors text-danger small">
<div class="form-group has-errors text-danger small">
<div class="form-group">
{% endfor %}
<button class="btn btn-primary" style="width:100%">Login</button>

note that it is requied to add the form-control class in the form input fields to style it in Bootstrap3.
So we will have to specify that css class in our file. we need to add attrs to the fields widget like shown below.

class SignUpForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password'}))

class Meta:
model = SignUp
fields = ['username','password']

Leave a Reply

Your email address will not be published.