In this shot, we look into how to create an instance of a table in the database using a function-based view in Django.
Let’s start with installation.
pipis a package manager for Python packages.
pip install pipenv
pipenv shell
pipenv install django
django-admin startproject crud ./
python manage.py startapp codebase
python manage.py migrate
python manage.py runserver
Go to settings.py and follow these steps.
settings.pyhelps register your app and packages that are being installed, and even writes rules.
settings.pyINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','codebase']
In the codebase app folder, go to:
models.pyThis file is responsible for creating the model for the database.
from django.db import modelsfrom django.urls import reverseclass CRUD(models.Model):name = models.CharField(max_length=30)age = models.IntegerField()level = models.CharField(max_length=30)date = models.DateTimeField(auto_now_add=True)#display the data with namedef __str__(self):return self.name
admin.pyIn this file, we register our model that has been created by importing it. By doing so, we can see it when logged in as an admin.
from django.contrib import adminfrom .models import CRUDadmin.site.register(CRUD)
Create a file and name it forms.py.
The forms file is responsible for creating Django forms, which are like HTML forms, but dynamic.
forms.pyfrom django import formsfrom .models import CRUDclass CRUDFORM(forms.ModelForm):name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control","placeholder": "name"}))age= forms.CharField(widget=forms.TextInput(attrs={'type': "number","class": "form-control","placeholder": "age"}))level = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control","placeholder": "level"}))class Meta:model = CRUDfields = ['name', 'age','level']
views.pyThis file is used to create functions or classes that visualize how a route will operate.
from django.shortcuts import redirect, render, get_object_or_404from .models import CRUDfrom .forms import CRUDFORMdef home(request):queryset = CRUD.objects.all().order_by('-date')context = {'queryset': queryset}return render(request, 'app/base.html', context)def create(request):form = CRUDFORM(request.POST or None)if request.method == "POST":if form.is_valid():form.save()return redirect ('home')context = {"form":form}return render(request, 'app/createform.html', context)
In the codebase app, create a folder and name it templates. Inside the templates folder, create another folder and name it app. Inside the app folder, create ‘base.html’ and 'createform.html' files.
base.html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Crud</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"></head><body><div class="container mt-3"><!-- this code block is used to used to create a url link --><a href="{% url 'create'%}" >link to create a form</a><hr><!-- this code bloack is used to loop the data in the database -->{% for data in queryset %}<div class="list-group mb-3"><a href="#" class="list-group-item list-group-item-action">Name: {{data.name}}</a><a href="#" class="list-group-item list-group-item-action">Age: {{data.age}}</a><a href="#" class="list-group-item list-group-item-action">Level: {{data.level}}</a></div>{% endfor %}<hr></div></body></html>
createform.html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Crud</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"></head><body><div class="container mt-5"><form method="POST" action=""><!-- for csrf token -->{% csrf_token %}<div class="form-group mb-3"><!-- double curly braces is used to display data from the database -->{{form.name}}{{form.name}}{{form.name.errors}}</div><div class="form-group mb-3">{{form.age}}{{form.age.errors}}</div><div class="form-group mb-3">{{form.level}}{{form.level.errors}}</div><input type="submit" class="btn btn-outline-success" ></form></div></body>
In the crud folder, in the urls.py file, do this.
urls.pyfrom django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),# including the codebase urls.py filepath('', include('codebase.urls'))]
Then, in the codebase folder, create a file and name it urls.py.
This file is responsible for creating different routes.
urls.pyfrom django.urls import pathfrom .views import home, createurlpatterns = [path('',home, name="home" ),path('create/', create, name="create"),]
Then, run the following commands.
python manage.py makemigrations
python manage.py migrate
In case you want to create a super-user, run the following command:
python manage.py createsuperuser
After that, run:
python manage.py runserver
Then, go at http://127.0.0.1:8000/admin and login in order to access the admin panel, or http://127.0.0.1:8000/ to access the homepage.