Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
django
communitycreator

How to style Django Forms with django-crispy-forms

Njoku Ifeanyi Gerald

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.


pip is 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 definition

INSTALLED_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 FORM
CRISPY_TEMPLATE_PACK = 'bootstrap4'
settings.py

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 models

class 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 admin
from .models import CrispyModel

admin.site.register(CrispyModel)
admin.py

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 forms
from django.db.models import fields
from .models import CrispyModel

class CrispyForm(forms.ModelForm):
  class Meta:
    model = CrispyModel
    fields = '__all__'
forms.py

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, render
from .forms import CrispyForm
from django.http import HttpResponse


def home(request):
    #referencing the Form
    #if it comes with a post request or a get request
    form = CrispyForm(request.POST or None)
    #if it is a post request
    if request.method == 'POST':
        #check if the form is valid enough to be saved
        if form.is_valid():
            #to save the form
            form.save()
            return redirect ('home')
        else:
            return HttpResponse('invalid form')
    context = {
        'form': form
    }
    return render(request, 'app/home.html', context)
        
views.py

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>
home.html

Step 10

In the DjangoCrispyForm folder, enter the following in the "urls.py" file.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    # including the codebase urls.py file
    path('', 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.py
from .views import home


urlpatterns = [
    path('', home, name='home'),
]
urls.py

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.

RELATED TAGS

python
django
communitycreator

CONTRIBUTOR

Njoku Ifeanyi Gerald
RELATED COURSES

View all Courses

Keep Exploring