Search code examples
pythonhtmlcssdjangotwitter-bootstrap

How can I add bootstrap styles to my django form?


I created a django form and output it in template. But I can't understand how I can add bootstrap styles 'cause this django form isn't good.

Image of output:

enter image description here

Code:

{% extends 'base.html' %}
{% block title %}
    Contact Us
{% endblock %}

{% block content %}
<h1>Contact Us</h1>
<form method="post">
        {% csrf_token %}

        {% for field in form %}
            <div class="form-group">
                {{ field.label }}
                {{ field }}
            </div>
        {% endfor %}
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
        <button class="btn btn-primary" type="submit" name="button">Send</button>
    </form>
{% endblock %}

Solution

  • To add bootstrap styling to your form, you're going to need to paste this code somewhere between your tags for the CSS;

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    

    And this for the JavaScript;

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    

    This will apply some styling to your form.
    Once you've done this, you'll have to use the classes that are specified on the BootStrap documentation that you can find here if you want to change the styling: https://getbootstrap.com/docs/4.1/components/forms/

    This should give you the styling that you want although you may want to add a bit of your own additionally to get exactly what you're after.