How to style Django Forms with django-crispy-forms
Introduction
Django doesn’t come with a form styling method, so it takes a lot of effort to style a Django form.
Django-crispy-forms solves this problem for us.
What is Django-crispy-forms?
Django-crispy-forms provides you with a crispy filter and {% crispy %} tag that lets you control the rendering behavior of your Django forms in an elegant and dry way.
You have full control without writing custom form templates. Django-crispy-forms avoids breaking the standard way of doing things in Django, as it operates well with any other form application.
How to install DjangoCrispForm
Let’s start with installation.
pipis a package manager for Python packages.
Step 1
pip install pipenv
pipenv shell
pipenv install django
Step 2
django-admin startproject DjangoCrispyForm ./
python manage.py startapp codebase
Step 3
python manage.py migrate
python manage.py runserver
Step 4
Go to settings.py and enter the following.
settings.py helps register your app and packages that are being installed write rules.
# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','codebase',# CRISPY FORM'crispy_forms']# CRISPY FORMCRISPY_TEMPLATE_PACK = 'bootstrap4'
Step 5
In the codebase app folder, go to models.py. This file is responsible for creating the model for the database.
from django.db import modelsclass CrispyModel(models.Model):songs = models.CharField(max_length=500)name_of_artist = models.CharField(max_length=500)number_of_awards = models.IntegerField()def __str__(self):self.songs
Step 6
Go to admin.py. In this file, we register our previously created model by importing it. By doing so, we can see the model when logged in as admin.
from django.contrib import adminfrom .models import CrispyModeladmin.site.register(CrispyModel)
Step 7
Create a file and name it forms.py. The forms file is responsible for creating Django forms, which is like an HTML form, but dynamic.
from django import formsfrom django.db.models import fieldsfrom .models import CrispyModelclass CrispyForm(forms.ModelForm):class Meta:model = CrispyModelfields = '__all__'
Step 8
The views.py file is used to create functions or classes that visualize how a route will operate.
from django.shortcuts import redirect, renderfrom .forms import CrispyFormfrom django.http import HttpResponsedef home(request):#referencing the Form#if it comes with a post request or a get requestform = CrispyForm(request.POST or None)#if it is a post requestif request.method == 'POST':#check if the form is valid enough to be savedif form.is_valid():#to save the formform.save()return redirect ('home')else:return HttpResponse('invalid form')context = {'form': form}return render(request, 'app/home.html', context)
Step 9
In the codebase app, create a folder and name it “templates.”
Inside the “templates” folder, create another folder and name it “app.” Then, inside the “app” folder, create the “home.html” file.
{% load crispy_forms_tags %}<!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>Document</title></head><body><form method="post" action="."><br>{% csrf_token %}{{form|crispy}}<br><button>Submit</button></form></body></html>
Step 10
In the DjangoCrispyForm folder, enter the following in the "urls.py" file.
from django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),# including the codebase urls.py filepath('', include('codebase.urls'))]
Step 11
Then, in the “codebase” folder, create a file and name it “urls.py”. This file is responsible for creating different routes.
from django.urls import path#importing home function from views.pyfrom .views import homeurlpatterns = [path('', home, name='home'),]
Step 12
Run the following commands:
python manage.py makemigrations
python manage.py migrate
The makemigration command
prepares the model to move into the database.
migrate moves the files or model to the database.
Step 13
If you want to create a super-user, run the following command:
python manage.py createsuperuser
Step 14
Run the following:
python manage.py runserver
Step 15
Then, go to http://127.0.0.1:8000/admin and login in order to access the admin panel, or go to http://127.0.0.1:8000 to access the homepage.