Abhishek
Abhishek

Reputation: 3068

Applying bootstrap to a django registration page

I have a django app where I am using authentication system with forms. I was following this tutorial to do it.

<div class="panel panel-default">
    {% if registered %}
    <strong>Thank you for registering!</strong>
    <a href="/lms/">Return to the homepage.</a><br />
    {% else %}
    <strong><h3>Register here!</h3></strong><br />
        <form id="user_form" method="post" action="/lms/register/" enctype="multipart/form-data">

            {% csrf_token %}

            {{ user_form.as_p }}
            {{ profile_form.as_p }}

            <input type="submit" name="submit" class="btn btn-primary" value="Register" />
        </form>
    {% endif %}
</div>

Now I am trying to add these forms in bootstrap labels. But since it is bringing all the elements of the forms in a single statement, how do I make these labels to show up using bootstrap?

Upvotes: 2

Views: 2556

Answers (3)

nicorellius
nicorellius

Reputation: 4043

The answers here are very good, and I've had success with Django Crispy forms (recommended in Two Scoops), and other libraries like django-bootstrap. But in case another option is desired, I use forms to tweak the fields:

class UserAuthenticationForm(LoginForm):

    username = forms.CharField(
        max_length=30,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'name': 'username',
                'placeholder': 'Username',
                'autofocus': 'autofocus',
            }
        )
    )

Build out all the fields you want. This gives finer control over exactly what you want the forms to look like. Then, for the template:

<form class="login" method="post" action="{% url 'account_login' %}">
    {% csrf_token %}
    {{ form }}
    . . .
    {# add errors, etc... #}
    <button class="btn btn-lg btn-primary" type="submit">
        {% trans "Log in" %}
    </button>
</form>

You can also override the views, if needed...

Upvotes: 0

cezar
cezar

Reputation: 12012

You don't have to output the form in the template in a single statement. You could do something like:

{% for field in user_form %}
    <p class="some-bootstrapclass">{{ field.label_tag }}{{ field }}</p>
{% endfor %}

This is very simplified example.

However I would strongly suggest you to take a look at crispy forms:

http://django-crispy-forms.readthedocs.org

With crispy forms you can set everything in your forms.py and still output the forms in a single statement in the template, for example:

{% load crispy_forms_tags %}

{% crispy user_form %}

Upvotes: 3

Zorig
Zorig

Reputation: 605

you can use specific fields name instead of using .as_p. For example let's assume that you have username and age field. Hence it will be like this

{{ user_form.username }}
{{ user_form.age }}

Hope it helped :)

Upvotes: 2

Related Questions