In this tutorial, we will learn how to do CRUD Operations using Django with SQLite Database. In this tutorial, we will Create, Retrieve, Update, and delete records from a database table. So, we will see a step-by-step procedure to do this.
After Creating the Django App let’s create a model that contains table name and fields
models.py
from django.db import models from Django import forms class tbl_Companydetails(models.Model): # Id = models.IntegerField() companyName = models.CharField(max_length = 150) Address = models.CharField(max_length = 500) contactNo = models.CharField(max_length=15) establisheddate = models.DateField(null=True, blank=True) websitelink = models.CharField(max_length=50,default='') emailaddress = models.CharField(max_length=50,default='') # companylogo =models.FileField() def __str__(self): return self.companyName ddlcompanyobjects = models. Manager()
After creating model then create forms.py file
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, Row, Column, Field from .models import tbl_Companydetails class Companymaster(forms.ModelForm): class Meta: model = tbl_Companydetails fields=['companyName','Address','contactNo','establisheddate','websitelink','emailaddress']
creating model execute commands
python manage.py makemigrations
python manage.py migrate
Then create a method to retrieve and insert data in a database table using view.
Views.py
from django.shortcuts import render,redirect from django.contrib.auth import login,authenticate from .models import tbl_Authentication,tbl_Companydetails from .forms import Companymaster from django.shortcuts import render, redirect ,get_object_or_404 from django.contrib import messages def CreatecompanyNew(request): ddlcompanyobjects= tbl_Companydetails.ddlcompanyobjects.all() if request.method == 'POST': form = Companymaster(request.POST) print(form.errors,form) if form.is_valid(): user = form.save(commit=False) user.save() return render(request,'company.html',{'form':form,'ddlcompanyobjects':ddlcompanyobjects}) else: form = Companymaster() return render(request,'company.html',{'form':form,'ddlcompanyobjects':ddlcompanyobjects})
edits existing records
def Editcompany(request, id): ddlcompanyobjects = tbl_Companydetails.ddlcompanyobjects.get(id=id) return render(request,'EditCompany.html', {'ddlcompanyobjects':ddlcompanyobjects}) def Updatecompany(request, id): print('t') obj= get_object_or_404(tbl_Companydetails, id=id) form = Companymaster(request.POST, instance= obj) context= {'form': form} print(obj) if form.is_valid(): ddlcompanyobjects = tbl_Companydetails.ddlcompanyobjects.all() user = form.save(commit=False) user.save() messages.success(request, "You successfully updated the Data") context= {'form': form} return render(request, 'company.html',{'form':form,'ddlcompanyobjects':ddlcompanyobjects}) else: context= {'form': form, 'error': 'The Data was not updated successfully.'} return render(request,'company.html' , context)
Delete a record in the table
def Deletecompany(request, id): ddlcompanyobjects = tbl_Companydetails.ddlcompanyobjects.get(id=id) ddlcompanyobjects.delete() return redirect('/CreatecompanyNew')
After that add the path to urls.py files
from django.urls import path from . import views urlpatterns = [ path("",views.base,name="base"), path('CreatecompanyNew/',views.CreatecompanyNew,name='CreatecompanyNew'), path('Editcompany/<int:id>', views.Editcompany,name="Editcompany"), path('Updatecompany/<int:id>', views.Updatecompany,name="Updatecompany"), path('Deletecompany/<int:id>', views.Deletecompany,name="Deletecompany"), ]
Once writing views and models is over then move to the templates folder to create html page named Company.html, here I am using Django with boostrap4.
{% block title %} Company {% endblock %} {% block content %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <form method="POST" enctype = "multipart/form-data" > {% csrf_token %} <div class="container shadow-lg"> <div class="row"> <div class="col-md-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Company Details</h2> <div class="clearfix"></div> </div> <div class="row"> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-6 col-sm-3 col-xs-12" for="name">Company Name <span class="required">*</span> </label> <input type="text" name="companyName" class="form-control" pattern="^[^\s][\w\W]*$" autocomplete="off" title="Enter Company Name. Dont Use Space At Start and Special Characters, You can use a combination of Alphabets and Numbers." minlength="1" maxlength="50" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode == 32)"/> </div> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Address<span class="required">*</span> </label> <input type="text" name="Address" class="form-control" /> </div> </div> <div class="row"> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Contact No<span class="required">*</span> </label> <input type="text" name="contactNo" class="form-control" pattern="[0-9]{10}" autocomplete="off" title="Enter Contact Number." minlength="10" maxlength="10" onkeypress="return (event.charCode >= 48 && event.charCode <= 57)"/> </div> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-4 col-sm-3 col-xs-12" for="name">Established date<span class="required">*</span> </label> <input type="date" name="establisheddate" class="form-control" /> </div> </div> <div class="row"> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Website URL<span class="required">*</span> </label> <input type="text" name="websitelink" class="form-control" /> </div> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Email address<span class="required">*</span> </label> <input type="text" name="emailaddress" class="form-control" /> </div> </div> <div class="row"> </div> <br/> <div class="form-group"> <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3"> <button type="submit" class="btn btn-success">Submit</button> <button class="btn btn-primary" type="reset">Reset</button> </div> </div> </div> <div class="x_content"> <div id="datatable_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer"> <div class="row"> <div class="col-sm-12"> <table id="datatable" class="table table-striped table-bordered dataTable no-footer" role="grid" aria-describedby="datatable_info"> <thead> <tr role="row"> <th hidden="true">SLNO</th> <th>Company Name</th> <th>Address</th> <th>Contact No</th> <th>Established Date</th> <th>Email</th> <th>Website Url</th> <th>Action</th> </tr> </thead> <tbody> {% for company in ddlcompanyobjects %} <tr style="background:#f8fcff"> <td class="align-middle" hidden="true">{{ company.id }}</td> <td class="align-middle" >{{ company.companyName }}</td> <td class="align-middle">{{ company.Address }}</td> <td class="align-middle">{{ company.contactNo }}</td> <td class="align-middle">{{ company.establisheddate }}</td> <td class="align-middle">{{ company.emailaddress }}</td> <td class="align-middle">{{company.websitelink}} </td> <td> <a href="/Editcompany/{{ company.id }}"><i class="fa fa-pencil"></i>Edit</a> <a href="/Deletecompany/{{ company.id }}"><i class="fa fa-trash-o"></i>Delete</a> </td> </tr> {% empty %} <tr> <td class="bg-light text-center font-italic" colspan="4">No Data</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </form> {% endblock %}
Editcompany.html
{% block title %} Company {% endblock %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% block content %} <form method="POST" action="/Updatecompany/{{ ddlcompanyobjects.id }}" enctype = "multipart/form-data" > {% csrf_token %} <div class="container shadow-lg"> <div class="row"> <div class="col-md-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Company Details</h2> <div class="clearfix"></div> </div> <div class="row"> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-6 col-sm-3 col-xs-12" for="name">Company Name <span class="required">*</span> </label> <input type="text" name="companyName" class="form-control" value="{{ ddlcompanyobjects.companyName }}" pattern="^[^\s][\w\W]*$" autocomplete="off" title="Enter Company Name. Dont Use Space At Start and Special Characters, You can use a combination of Alphabets and Numbers." minlength="1" maxlength="50" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode == 32)"/> </div> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Address<span class="required">*</span> </label> <input type="text" name="Address" class="form-control" value="{{ ddlcompanyobjects.Address }}"/> </div> </div> <div class="row"> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Contact No<span class="required">*</span> </label> <input type="text" name="contactNo" class="form-control" value="{{ ddlcompanyobjects.contactNo }}" pattern="[0-9]{10}" autocomplete="off" title="Enter Contact Number." minlength="10" maxlength="10" onkeypress="return (event.charCode >= 48 && event.charCode <= 57)"/> </div> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-4 col-sm-3 col-xs-12" for="name">Established date<span class="required">*</span> </label> <input type="date" name="establisheddate" class="form-control" value="{{ ddlcompanyobjects.establisheddate|date:"Y-m-d"}}" /> </div> </div> <div class="row"> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Website URL<span class="required">*</span> </label> <input type="text" name="websitelink" class="form-control" value="{{ ddlcompanyobjects.websitelink }}" /> </div> <div class="form-group col-md-6 mb-0"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Email address<span class="required">*</span> </label> <input type="text" name="emailaddress" class="form-control" value="{{ ddlcompanyobjects.emailaddress }}"/> </div> </div> <div class="row"> </div> <br/> <div class="form-group"> <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3"> <button type="submit" class="btn btn-success">Submit</button> <button class="btn btn-primary" type="reset">Reset</button> </div> </div> </div> </div> </div> </div> </form> {% endblock %}
then execute command
python manage.py runserver