Django How to Use Bootstrap 4 Forms using Django Crispy Forms module
Crispy-forms is a great application that gives you control over how you render Django forms, without breaking the default behavior.
Install it using pip:
pip install django-crispy-forms
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
#models.py from django.db import models # Create your models here. class StudentForm(models.Model): firstname = models.CharField("Enter first name", max_length=50) lastname = models.CharField("Enter last name", max_length = 50) email = models.EmailField("Enter Email") bio = models.TextField(blank=True) file = models.FileField() # for creating file input class Meta: db_table = "student"
#views.py from django.shortcuts import render from myapp.forms import StudentForm #forms.py from django.http import HttpResponse from myapp.functions import handle_uploaded_file #functions.py def index(request): if request.method == 'POST': student = StudentForm(request.POST, request.FILES) if student.is_valid(): handle_uploaded_file(request.FILES['file']) model_instance = student.save(commit=False) model_instance.save() return HttpResponse("Record successfuly added") else: student = StudentForm() return render(request,"student_form.html",{'form':student})
#forms.py from django import forms from myapp.models import StudentForm #models.py class StudentForm(forms.ModelForm): class Meta: model = StudentForm fields = "__all__"
//templates/student_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} <!-- {{ form|crispy }} --> <div class="row"> <div class="col-6"> {{ form.firstname|as_crispy_field }} </div> <div class="col-6"> {{ form.lastname|as_crispy_field }} </div> </div> {{ form.email|as_crispy_field }} {{ form.bio|as_crispy_field }} {{ form.file|as_crispy_field }} <button type="submit" class="btn btn-success">Save Student</button> </form> {% endblock %}
//templates/base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Django Student</title> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <h1 class="mt-2">Django Student</h1> <h3>Django How to Use Bootstrap 4 Forms using Django Crispy Forms module</h3> <hr class="mt-0 mb-4"> {% block content %} {% endblock %} </div> </div> </div> </body> </html>
#functions.py def handle_uploaded_file(f): with open('myapp/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk)
#urls.py from django.contrib import admin from django.urls import path from myapp import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), ]
CREATE TABLE student (
id INTEGER PRIMARY KEY,
firstname STRING (50),
lastname STRING (50),
email STRING (50),
file STRING (255),
bio TEXT
);