How to create form with Django Crispy Forms

In this Python Django tutorial, I will explain how to create form with Django Crispy Forms step by step.

Recently, I have been working on a contact form using bootstrap and I have found that it requires dozen of lines of code and takes a lot of effort, so I have done some research and found that Django offers crispy forms.

Here we will see:

  • What are Django Crispy Forms
  • How to use Django Crispy Forms
  • How to build a contact form using Crispy Forms in Django
  • How to use various controls like textbox, textarea, and email in Django from
  • How to create Django form with email using Crispy Forms
  • How to view submitted data from the Django admin interface

There are different ways, we can create forms in Django like using forms, HTML, etc. But they lack a stylized appearance, so we will focus on rendering a Django form using Django crispy forms here.

At the end of this article, you can also download the code: Create Django form with Django Crispy Forms.

This is what we will build here.

create form with Django Crispy Forms
Create Form with Django Crispy Forms

How to create Form with Django Crispy Forms

Now, let us see, step by step how to create a Django form with Django Crispy Forms.

Django Crispy Forms

In Django, django-crispy-form is a Python package with built-in support for the Bootstrap CSS and Bootstrap CDB framework.

It allows us to integrate Bootstrap into our project with fewer lines of code and less effort.

How to setup Django Crispy Forms

Django-crispy-forms should first be installed in your activated virtual environment. With the help of this package, we can render Django forms without using any additional custom form CSS.

pip install django-crispy-forms

After the installation is completed add the Django crispy_forms to INSTALLED_APPS inside the settings.py file.

django contact form using crispy forms
settings.py

Now, add the CRISPY_TEMPLATE_PACK, below the INSTALLED_APP list, to provide built-in support for various CSS and bootstrap frameworks.

And set its value equivalent to the bootstrap that we are using. Here I, set its value to bootstrap4.

python django contact form using crispy forms
Crispy Template Pack

Read: Simple Contact Form for website in Python Django

How to create form with Django Crispy Forms

Set up Django Project

Firstly, create a project in Django named WebsiteBuilder using the below-given command.

django-admin startproject WebsiteBuilder

Create a Django app named Contact, within the Django project, by typing the below command in the terminal.

python manage.py startapp Contact

Add the Contact app to the installed app list located in the settings.py file.

contact form using crispy form in django
settings.py

A file named urls.py is automatically included by Django in the project directory. Inside it, maps the recently created app Contact as given below.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('Contact.urls')),
]

Read: How to create web form in Python Django

Create form from model in Django

Open the models.py file located in the app directory to create models and add the following code there.

from django.db import models

# Create your models here.

class Contact(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()
    message = models.TextField(max_length=1000)
    
    def __str__(self):
        return self.email

Here, we create a model class Contact which has the following fields.

  1. The name is Django CharFields to take name input from the user. And there is a 50-character limit for this character field.
  2. The email is Django EmailField which allows users to save email addresses.
  3. The message field is Django TextField. And there is a 1000-character limit for it.

And to change the display name of the object in the Django model use the def __str__(self). It will render the item name as email as we return the self.email.

To register the Contact model with the admin site, open the admin.py file and add the below-given code.

from django.contrib import admin
from .models import Contact

# Register your models here.

admin.site.register(Contact)

Create the Django form that the Contact application will use to collect user input. Add the following code to the forms.py file you create inside the app directory.

from django import forms
from .models import Contact

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = '__all__'

Here, we define a form class called ContactForm that has all the fields from the Contact model.

Read: How to create Contact Form with Django and SQLite

Create Templates

In Django, the front end of the application is defined in Templates, so for this, create a subdirectory called Templates in the main project directory to store all of the project templates.

Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.

contact form using crispy form in python django
settings.py

To define the front end of the contact form, create an HTML file named contact.html inside the Templates folder and include the code given below.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Contact Us</title>
</head>

<body>
    <form method="post">
        {% load crispy_forms_tags %}
        {% csrf_token %}
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-8">
                    <h1 class="mt-4" align="center">Contact Us</h1>
                    <hr class="mt-4 mb-5">
                    <h4 class="mt-4" align="center">Let's get conversation started. Tell us a bit about yourself, and our team will get in touch as soon as we can.</h4>
                    <hr class="mt-4 mb-5">
                    <div class="row">
                        <div class="col-6">
                            {{ form.name|as_crispy_field }}
                        </div>
                        <div class="col-6">
                            {{ form.email|as_crispy_field }}
                        </div>
                    </div>
                    <div>
                        {{ form.message|as_crispy_field }}
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </div>
        </div>    
    </form>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <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.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
</body>

</html>

First, load your CSS by adding the stylesheet’s link to our page’s header before any other stylesheets.

Now describe your contact form using the form tag with the POST method and load the crsf_token tag to protect our form from cyber attacks.

Then, to style the Django form with bootstrap rows and columns, load the crispy_form_tag and to call each form field individually, use {{form.name_of_field|as_crispy_field}} tag.

The functionality of several of our components depends on JavaScript and to enable the following scripts, add them before the closing body tag.

We want to render the contact form to another page when it is successfully submitted, so we receive the success message and the contact form link once again.

To do this, we add another HTML file called success.html to the Template Folder.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Success</title>
</head>

<body>
    <h2 style="text-align: center; color: red;" "></h2style>We sent your message</h2>
    <p> You can send another in the <a href=" {% url 'contact' %}">Contact Page</a></p>
</body>

</html>

First, we define the heading using the h2 tag, and to center the text and set its color to red, we pass text-align and color attributes inside the tag. Then, inside the p tag, the contact page is linked to using the a href tag.

Read: Build a Django Contact Form with Email

Define Django View

To create the main logic for the creation of the contact form using the crispy form, we open the views.py file and add the below-given code.

from django.shortcuts import render
from .forms import ContactForm

# Create your views here.

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'success.html')
    form = ContactForm()
    context = {'form': form}
    return render(request, 'contact.html', context)

First import the ContactForm from the forms.py, then call the if statement and check whether the request method is POST.

If yes, we pass ContactForm(request.POST) that binds the data to the form class, so we can do validation. Now, call the is_valid() to validate the input entered by the user, and if validation success save the data using the save(), and render the user to the success.html.

If not, the user is presented with a blank contact form using the render() function.

We must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.

from django.urls import path
from Contact import views

urlpatterns = [
    path("contact", views.contact, name="contact"),   
]

Read: Python Django vs Flask – Key Differences

Create form with Django Crispy Forms and Email

Additionally, this contact form is connected to the email backend, which functions automatically and notifies the user through email each time the form is submitted on behalf of the website staff.

To add the settings required for Django to send emails, open the settings.py file and add the following code.

# Email Settings

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = #sender email-id
EMAIL_HOST_PASSWORD = #password associated with sender email-id

Open the views.py file and add the following code to send the email on the submission.

from django.shortcuts import render
from .forms import ContactForm
from django.core.mail import send_mail
from django.conf import settings

# Create your views here.

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            subject = "Welcome to PythonGuides Website Builder"
            message = "Our team will contact you within 24hrs."
            email_from = settings.EMAIL_HOST_USER
            email = form.cleaned_data['email']
            recipient_list =email
            send_mail(subject, message, email_from, [recipient_list])
            return render(request, 'success.html')
    form = ContactForm()
    context = {'form': form}
    return render(request, 'contact.html', context)

Import the settings variable, which contains all of the global settings found in the settings.py file, and the Django send_mail function.

Then, provide the arguments we’ll need while composing an email and pass all the arguments to the send_mail() function which is responsible for email sending in Django.

Read: Python Django get admin password

Execute Django Application

In order to begin working with the model, we must first create a migration for the given model. Use the terminal to execute the following command.

python manage.py makemigartions

We must migrate the database in order to reflect it. Below is the migrate command.

python manage.py migrate

We enter the command below into the terminal to launch a development server for this particular Django project.

python manage.py runserver

By expanding the URL as shown below, we can access the contact form.

127.1.1.0/contact

It successfully opens the Django contact form that we create using the crispy form which looks like this.

using crispy form build django contact form
Create Form with Django Crispy Forms

Now, fill out the contact form and click the submit button as shown below.

how to build contact form using django using crispy form
Contact Us form using the Django crispy form

Once we click submit, we’ll be taken to the success page. If we hit the Contact Page link, we will again be taken to a contact form that is unfilled.

django contact form using crispy package
Success Page

Additionally, after clicking the submit button, an email will be sent from the website owner’s email to the user’s email which they fill in the form.

python django contact form using crispy package
Website Owner Email
contact form using crispy package in django
User Email

Read: Python Django vs Pyramid

View submitted data from the Django admin interface

Django provides its users with an admin interface via which they may view the information they saved from the form to the database.

For this, we must create a superuser using the below-given command.

python manage.py createsuperuser

Under the CONTACT app, select contacts. And we will get the form data recorded in the database.

build contact form using django crispy forms
Admin Site

This is how we can render a Django contact form using crispy forms.

Read: How to build a contact form in Django using bootstrap

Download the create form with Django crispy forms complete code

Here is the code.

Conclusion

With this, we have successfully created a working form with Django Crispy Forms that make use of a database and crispy form. We have also learned how to send automatic emails from the website owner to users who have filled out the form.

Additionally, we have also covered the following topics.

  • What are Django Crispy Forms
  • How to use Django Crispy Forms
  • How to create form with Django Crispy Forms
  • How to use various controls like textbox, textarea, and email in Django from
  • How to create form with Django Crispy Forms and email
  • How to view submitted data from the Django admin interface

You may also like to read the following Python Django tutorials.