Tech
Infected

Linux, OpenSource, Programming And Hacks

Nov 14, 2016

How to style Django Forms with Bootstrap

Nov 14, 2016

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>
<html>
    <head>
        <title></title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <h1>Example Form</h1>
            <div style="width:30%">
                <form action="">
                    {%csrf_token%}
                    {% for error in form.non_field_errors %}
                    <div class="form-group has-errors text-danger small">
                        {{error}}
                    </div>
                    {% endfor %}
                    {% for field in form %}
                    <div class="form-group has-errors text-danger small">
                        {{field.errors}}
                    </div>
                    <div class="form-group has-errors text-danger small">
                    </div>
                    <div class="form-group">
                        {{field}}
                    </div>
                    {% endfor %}
                    <button class="btn btn-primary" style="width:100%">Login</button>
            </div>
            </form>
        </div>
    </body>
</html>

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 forms.py 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']


No comments:

Post a Comment