The post How to Add Pagination in Django Python appeared first on Tech Insights.
]]>What is Pagination – Pagination is the process of distributing a website’s content across multiple pages.
Django has a built in Paginator class.
How to Use – First we need to import it “Paginator class” from django.core.paginator.
models.py
from django.db import models # Create your models here. class MenuList(models.Model): Menucode= models.IntegerField() MenuType=models.IntegerField() menuname = models.CharField(max_length=100) submenuname = models.CharField(max_length=100) menulink = models.CharField(max_length=100) def __str__(self): return self.menuname objects = models.Manager()
urls.py
from django.contrib import admin from django.urls import path from .views import Menu_list urlpatterns = [ path("",Menu_list,name="Employee"), ]
views.py
from django.shortcuts import render from .models import MenuList from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage # Create your views here. def Menu_list(request): Result_set = MenuList.objects.all() page_list = request.GET.get('page',1) pages = Paginator(Result_set,5) try: result_page = pages.page(page_list) except PageNotAnInteger: result_page = pages.page(1) except EmptyPage: result_page = pages.page(pages.num_pages) return render(request,'menulist.html',{'menulist':result_page})
<html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <div class="container"> <div class="shadow p-3 mb-5 bg-grey rounded"> <table class="table table-bordered"> <thead> <tr> <th> SLNo </th> <th> Menu Name</th> <th> Sub Menu Name</th> </tr> </thead> <tbody> {% for menu in menulist %} <tr> <td>{{ menu.Menucode }} </td> <td>{{ menu.menuname }} </td> <td> {{ menu.submenuname }} </td> </tr> {% endfor %} </tbody> </table> <ul class="pagination"> {% if menulist.has_previous %} <li class="page-item"><a href="?page={{ menulist.previous_page_number }}">Previous</a></li> {% else %} <li class="page-item disabled"><span>Previous</span></li> {% endif %} {% for k in menulist.paginator.page_range %} {% if menulist.number == k %} <li class="page-item active"><span>{{ k }}<span class="sr-only">(current)</span></span></li> {% else %} <li class="page-item"><a href="?page={{k}}">{{k}}</a></li> {% endif %} {% endfor %} {% if menulist.has_next %} <li class="page-item"><a href="?page={{ menulist.next_page_number }}">Next</a></li> {% else %} <li class="page-item disabled"><span>Next</span></li> {% endif %} </ul> </div> </div> </body> </html>
The post How to Add Pagination in Django Python appeared first on Tech Insights.
]]>The post How to Create Cascading/Dependent Dropdown List in Django Python appeared first on Tech Insights.
]]>In this tutorial, we will learn How to Create a Cascading/Dependent Dropdown List in Django Python. In this small application, we are going to improve user experience by Creating a dynamic Django dropdown list using jQuery.
We need to create a Django project dropdownfill
Django-admin startproject dropdownfill
Now then need to create an app dropdown to perform the Cascading/Dependent Dropdown List in Django Python.
python manage.py startapp dropdownfill
Configure application settings by registering the App_name into the settings.py in a specific location at INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dropdown', ]
Now we need to create models.py .
from django.db import models from django.db.models.base import Model from django.db.models.deletion import CASCADE # Create your models here. class department(models.Model): departmentname = models.CharField(max_length=100) class employee(models.Model): deptid = models.ForeignKey(department,on_delete=CASCADE) empname = models.CharField(max_length=100) age = models.IntegerField() address = models.CharField(max_length=500, null=True) contactno = models.CharField(max_length=20)
views.py
from django.http.response import HttpResponse, JsonResponse from django.shortcuts import render from .models import department,employee from django.core import serializers import json # Create your views here. def getdata(request): template_name = 'dropdown.html' deptcontext = department.objects.all() empcontext = employee.objects.all() return render(request,template_name,{'department':deptcontext, 'employee':empcontext})
https://labpys.com/how-to-upload-files-images-in-django-python/
We need to add dropdown.urls to main project urls.py
urls.py
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('dropdown.urls')), ]
Create urls.py file inside dropdown app to write the URL pattern or providing routing for the application.
urls.py
from django.urls.conf import path from dropdown import views urlpatterns = [ path('getdata/',views.getdata,name="getdata"), ]
Create a template folder inside dropdown app and create html file in the directory.
dropdown.html
<!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>DropDown</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <h1><center>How to Create Cascading/Dependent Dropdown List in Django python</center></h1> <div class="container"> <div class="card body"> <br/> <br/> <br/> <div class="row"> <div class="col-md-4"> <select name="dept" id="department" class="form-control"> <option value="0">--Select Department--</option> {% for item in department %} <option value="{{ item.id }}">{{ item.departmentname }}</option> {% endfor %} </select> </div> <br/> <div class="col-md-4"> <select name="emp" id="Employee" class="form-control"> <option value="0">--Select Staff--</option> {% for item in employee %} <option value="{{ item.deptid_id }}">{{ item.empname }}</option> {% endfor %} </select> </div> </div> </div> </div> <script> $(document).ready(function(){ var department = $("#department"); var Employee = $("#Employee"); var $options = Employee.find('option'); department.on('change',function(){ Employee.html($options.filter('[value="'+ this.value +'"]')); }).trigger('change'); }); </script> </body> </html>
Now make migrations
Python manage.py makemigrations
Python manage.py migrate
Python manage.py runserver
Please leave your comments and suggestion
The post How to Create Cascading/Dependent Dropdown List in Django Python appeared first on Tech Insights.
]]>The post How to create Dynamic menu from Database using Django Python appeared first on Tech Insights.
]]>A database-driven dynamic menu is very helpful.
This article creates a dynamic menu from the MYSQL database, Django, and Python.
Let’s start
This article uses Rest Framework “How to Create Dynamic menu from Database using Django Python”.
pip install djangorestframework
Create table in mysql
CREATE TABLE `dynamicmenu_mainmenu` ( `id` bigint(20) NOT NULL, `menucode` int(11) NOT NULL, `menuname` varchar(100) NOT NULL, `menutype` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `dynamicmenu_menulist` ( `id` bigint(20) NOT NULL, `Menucode` int(11) NOT NULL, `MenuType` int(11) NOT NULL, `menuname` varchar(100) NOT NULL, `submenuname` varchar(100) NOT NULL, `menulink` varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Insert the Data into a particular table using the below SQL insert statement
INSERT INTO `dynamicmenu_mainmenu` (`id`, `menucode`, `menuname`, `menutype`) VALUES(1, 1, 'Administrator', 1),(2, 2, 'Bank Account', 2),(3, 3, 'Deposit', 3),(4, 4, 'Withdraw', 4),(5, 5, 'Insurance', 5),(6, 6, 'Mutual Fund', 6),(7, 7, 'Employee', 7),(8, 8, 'Attendance', 8),(9, 9, 'Pigmy', 9),(10, 10, 'Pigmy Collection', 10); INSERT INTO `dynamicmenu_menulist` (`id`, `Menucode`, `MenuType`, `menuname`, `submenuname`, `menulink`) VALUES(1, 1, 1, 'Administrator', 'Bank', ''),(2, 2, 1, 'Administrator', 'Branch', ''),(3, 3, 1, 'Administrator', 'Department', ''),(4, 4, 1, 'Administrator', 'Company', ''),(5, 5, 2, 'Bank Account', 'Bank Account', ''),(6, 3, 3, 'Deposit', 'Deposit', ''),(7, 4, 4, 'Withdraw', 'Withdraw', ''),(8, 5, 5, 'Insurance', 'Insurance', ''),(9, 6, 6, 'Mutual Fund', 'Mutual Fund', ''),(10, 7, 7, 'Employee', 'Employee', ''),(11, 8, 8, 'Attendance', 'Attendance', ''),(12, 9, 9, 'Pigmy', 'Pigmy', ''),(13, 10, 10, 'Pigmy Collection', 'Pigmy Collection', '');
# Database
MySQL database settings
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangodb', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } }
Now Create Model
models.py
from django.db import models # Create your models here. class mainmenu(models.Model): menucode = models.IntegerField() menuname = models.CharField(max_length=100) menutype = models.IntegerField() def __str__(self): return self.menuname mainmenulist_objects =models.Manager() class MenuList(models.Model): Menucode= models.IntegerField() MenuType=models.IntegerField() menuname = models.CharField(max_length=100) submenuname = models.CharField(max_length=100) menulink = models.CharField(max_length=100) def __str__(self): return self.menuname menulist_objects = models.Manager()
Then create serializers.py
from rest_framework import serializers from .models import MenuList class menuserializer(serializers.ModelSerializer): class Meta: model = MenuList fields =['menuname'] class submenuserializer(serializers.ModelSerializer): class Meta: model = MenuList fields =['menuname','submenuname','menulink','MenuType']
views.py
from django.shortcuts import render from .models import MenuList,mainmenu from .serializers import menuserializer,submenuserializer from django.db.models import Avg, Count, Min, Sum # Create your views here. def dynamicmenu(request): try: menuList = MenuList.menulist_objects.values('menuname').order_by('MenuType').annotate(Count('menuname')) submenuList = MenuList.menulist_objects.all().filter(id__in=[1,2,3,4,5,6,7,8,9,10]) mainmenu = menuserializer(menuList,many=True) data = mainmenu.data # print(data) request.session['mainM'] = data submenudata = submenuserializer(submenuList,many=True) subdata = submenudata.data print(subdata) request.session['submenu'] = subdata return render(request, 'index.html', {}) except Exception as identifier: return render(request, 'index.html', {})
index.html
{% block content %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Collapsible sidebar using Bootstrap 3</title> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- Our Custom CSS --> <!-- Scrollbar Custom CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css"> <style> /* DEMO STYLE */ @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700"; body { font-family: 'Poppins', sans-serif; background: #fafafa; } p { font-family: 'Poppins', sans-serif; font-size: 1.1em; font-weight: 300; line-height: 1.7em; color: #999; } a, a:hover, a:focus { color: inherit; text-decoration: none; transition: all 0.3s; } .navbar { padding: 15px 10px; background: #fff; border: none; border-radius: 0; margin-bottom: 40px; box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1); } .navbar-btn { box-shadow: none; outline: none !important; border: none; } .line { width: 100%; height: 1px; border-bottom: 1px dashed #ddd; margin: 40px 0; } /* --------------------------------------------------- SIDEBAR STYLE ----------------------------------------------------- */ .wrapper { display: flex; width: 100%; align-items: stretch; } #sidebar { min-width: 250px; max-width: 250px; background: #7386D5; color: #fff; transition: all 0.3s; } #sidebar.active { margin-left: -250px; } #sidebar .sidebar-header { padding: 20px; background: #6d7fcc; } #sidebar ul.components { padding: 20px 0; border-bottom: 1px solid #47748b; } #sidebar ul p { color: #fff; padding: 10px; } #sidebar ul li a { padding: 10px; font-size: 1.1em; display: block; } #sidebar ul li a:hover { color: #7386D5; background: #fff; } #sidebar ul li.active>a, a[aria-expanded="true"] { color: #fff; background: #6d7fcc; } a[data-toggle="collapse"] { position: relative; } .dropdown-toggle::after { display: block; position: absolute; top: 50%; right: 20px; transform: translateY(-50%); } ul ul a { font-size: 0.9em !important; padding-left: 30px !important; background: #6d7fcc; } ul.CTAs { padding: 20px; } ul.CTAs a { text-align: center; font-size: 0.9em !important; display: block; border-radius: 5px; margin-bottom: 5px; } a.download { background: #fff; color: #7386D5; } a.article, a.article:hover { background: #6d7fcc !important; color: #fff !important; } /* --------------------------------------------------- CONTENT STYLE ----------------------------------------------------- */ #content { width: 100%; padding: 20px; min-height: 100vh; transition: all 0.3s; } /* --------------------------------------------------- MEDIAQUERIES ----------------------------------------------------- */ @media (max-width: 768px) { #sidebar { margin-left: -250px; } #sidebar.active { margin-left: 0; } #sidebarCollapse span { display: none; } } </style> </head> <body> <div class="wrapper"> <!-- Sidebar Holder --> <nav id="sidebar"> <div class="sidebar-header"> <h3>Dynamic Menu</h3> </div> <ul class="list-unstyled components"> {% for item in request.session.mainM %} <li class="active"> <a href="#{{ item.menuname }}" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">{{ item.menuname }}</a> <ul class="collapse list-unstyled" id="{{ item.menuname }}"> {% for value in request.session.submenu %} {% ifequal value.menuname item.menuname %} <li><a href="/{{ value.menulink }}">{{ value.submenuname }}</a></li> {% endifequal %} {% endfor %} </li> </ul> {% endfor %} </ul> </nav> <!-- Page Content Holder --> <div id="content"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn"> <i class="glyphicon glyphicon-align-left"></i> <span>Toggle Sidebar</span> </button> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Page</a></li> </ul> </div> </div> </nav> </div> </div> <!-- jQuery CDN --> <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <!-- Bootstrap Js CDN --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- jQuery Custom Scroller CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); }); }); </script> </body> </html> {% endblock %}
See More: How to Upload Files in Django Python
Now then Execute
The post How to create Dynamic menu from Database using Django Python appeared first on Tech Insights.
]]>The post How to Upload Files in Django Python appeared first on Tech Insights.
]]>It is generally the most common requirement in any modern web application is the ability to take files like profile pictures, pdf, word docs, and images from the user and save the theme on the server.
Django has two model fields such as FileField and ImageField.
The uploaded files are stored in the file system, not in the database. Now we can create a string field to reference to the file or image.
HTML
It is mandatory for the html form to have the attribute enctype=”mulipart/form-data”.
The form must be POST method to submit the form.
fileupload.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} {% block content %} <div class="row"> <div class="col-md-6 col-xs-12"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="fileupload" class="form-control"> <button type="submit" class="btn btn-success">submit</button> </form> {% if uploaded_url %} <p>File Uploaded at :<a href ="{{uploaded_url}}">{{ uploaded_url }}</a></p> {% endif %} </div> </div> {% endblock %}
Django
You will need to set MEDIA_URL and MEDIA_ROOT in your projects.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
And now add the following configuration in the projects urls.py files
urls.py
from django.conf import settings from django.conf.urls.static import static urlpatterns = [] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
File Upload using File System Storage
views.py
from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage def File_Upload(request): try: if request.method == 'POST' and request.FILES['fileupload']: pfile = request.FILES['fileupload'] filesys =FileSystemStorage() uploadfilename = filesys.save(pfile.name,pfile) uploaded_url = filesys.url(uploadfilename) return render(request, 'fileupload.html' ,{'uploaded_url':uploaded_url}) except Exception as identifier: print(identifier) return render(request,'fileupload.html',{})
Uploading Files with Model Form
Let’s start by creating models.
models.py
class Files(models.Model): filename = models.CharField(max_length=150) uploadimage = models.ImageField(upload_to='profile_pic') def __str__(self): return self.filename
forms.py
from .models import Files class employeeprofile(forms.ModelForm): class Meta: model = Files fields = ('filename','uploadimage')
views.py
from .forms import employeeprofile def File_upload_model(request): form = employeeprofile() try: if request.method == 'POST': form = employeeprofile(request.POST, request.FILES) if form.is_valid(): form.save() profile_pic = form.instance return render(request, 'empprofile.html',{'form':form,'profile_pic':profile_pic}) else: form = employeeprofile() return render(request , 'empprofile.html',{'form':form}) except Exception as identifier: print(identifier) return render(request,'empprofile.html',{'form':form})
urls.py
from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('File_Upload/', views.File_Upload,name="File_Upload"), path('File_upload_model/', views.File_upload_model,name="File_upload_model"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
HTML – empprofile.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} {% block content %} <div class="row"> <div class="col-md-6 col-xs-12"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <button type="submit" class="btn btn-success">submit</button> </form> {% if profile_pic %} <p>File Uploaded at :<a href ="{{profile_pic.filename}}">{{ profile_pic.filename }}</a></p> <img src="{{profile_pic.upload_image.url}}" alt ="connect" style="max-height:300px"> {% endif %} </div> </div> {% endblock %}
The post How to Upload Files in Django Python appeared first on Tech Insights.
]]>The post How to Export Data from the Database into Excel using Django Python appeared first on Tech Insights.
]]>Let’s start
Install pandas library
First, create a Django project, then create models
models.py
from django.db import models from Django import forms class tbl_Employee(models.Model): # Id = models.IntegerField() Empcode = models.CharField(max_length=10, default='') firstName = models.CharField(max_length=150,null=True) middleName = models.CharField(max_length=100,null=True) lastName = models.CharField(max_length=100,null=True) email = models.CharField(max_length=30,null=True) phoneNo = models.CharField(max_length=12, default='',null=True) address = models.CharField(max_length=500, default='',null=True) exprience = models.CharField(max_length=50, default='',null=True) DOB = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, default='',null=True) qualification = models.CharField(max_length=50,default='',null=True) def __str__(self): return self.firstName objects = models.Manager()
let's migrate model python manage.py makemigrations python manage.py migrate
forms.py
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_Employee class EmployeeRegistration(forms.ModelForm): class Meta: model = tbl_Employee fields =[ 'Empcode','firstName','middleName','lastName','email','phoneNo' ,'address','exprience', 'DOB','gender','qualification' ]
Then let’s write a code in views.py to create a function to Export data from the database into Excel.
Views.py
from .models import tbl_Employee import datetime as dt import pandas as pd import os from django.conf import settings from django.core.files.storage import FileSystemStorage import csv def export_users_csv(request): if request.method == 'POST': response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="EmployeeData.csv"' writer = csv.writer(response) writer.writerow(['Employee Detail']) writer.writerow(['Employee Code','Employee Name','Relation Name','Last Name','gender','DOB','e-mail','Contact No' ,'Address' ,'exprience','Qualification']) users = tbl_Employee.objects.all().values_list('Empcode','firstName' , 'middleName' , 'lastName','gender','DOB','email','phoneNo' ,'address','exprience','qualification') for user in users: writer.writerow(user) return response return render(request, 'exportexcel.html')
then add the path to the urls file
urls.py
from django.urls import path from . import views urlpatterns = [ path("",views.base,name="base"), path("user_login/",views.user_login,name="user_login"), path('export_users_csv/', views.export_users_csv,name="export_users_csv"), ]
Create a template folder in the root directory or app directory and a create html file named exportexcel.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% block content %} <div class="shadow-lg continer"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-6 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Data Export</h2> <div class="clearfix"></div> </div> <div class="x_content"> <div class="row"> <div class="col-md-8 col-sm-12 col-xs-12 form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-6" for="name">Company<span class="required">*</span> </label> </div> </div> <button type="submit" class="btn btn-success" >Export</button> </div> </div> </div> </div> </form> </div> {% endblock %}
Then execute command Python manage.py runserver
See More: Import Data from Excel into Database using Django
The post How to Export Data from the Database into Excel using Django Python appeared first on Tech Insights.
]]>The post Import Data from Excel into Database using Django appeared first on Tech Insights.
]]>We need to create a Django project Import_Excel
Django-admin startproject Import_Excel
Now then we will create a app import_excel_db to perform import data from excel into database.
python manage.py startapp import_excel_db
Pandas pip install pandas Django-import-export pip install Django-import-export
Configure application settings by registering the App_name into the settings.py in a specific location at INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'import_excel_db', ]
Now we need to create an employee model.
from django.db import models # Create your models here. class Employee(models.Model): Empcode = models.CharField(max_length=10, default='') firstName = models.CharField(max_length=150,null=True) middleName = models.CharField(max_length=100,null=True) lastName = models.CharField(max_length=100,null=True) email = models.CharField(max_length=30,null=True) phoneNo = models.CharField(max_length=12, default='',null=True) address = models.CharField(max_length=500, default='',null=True) DOB = models.DateField(null=True, blank=True) gender = models.CharField(max_length=5, default='',null=True) qualification = models.CharField(max_length=50,default='',null=True) salary = models.FloatField(max_length=50,default='',null=True) def __str__(self): return self.firstName objects = models.Manager()
Import data from Excel into the database using the Django-import-export library and this library works with the concept of Resource. So we need to create a resources.py file in the app folder.
from import_export import resources from .models import Employee class EmployeeResource(resources.ModelResource): class Meta: model = Employee
from http.client import HTTPResponse
from django.shortcuts import render
import os
from django.core.files.storage import FileSystemStorage
# Create your views here.
def Import_Excel_pandas(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request. FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'Import_excel_db.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'Import_excel_db.html',{})
views.py
Importing data from Excel into database using Pandas library
from http.client import HTTPResponse from django.shortcuts import render import pandas as pd import os from django.core.files.storage import FileSystemStorage from .models import Employee # Create your views here. def Import_Excel_pandas(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request. FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) empexceldata = pd.read_excel(filename) dbframe = empexceldata for dbframe in dbframe.itertuples(): obj = Employee.objects.create(Empcode=dbframe.Empcode,firstName=dbframe.firstName, middleName=dbframe.middleName, lastName=dbframe.lastName, email=dbframe.email, phoneNo=dbframe.phoneNo, address=dbframe.address, gender=dbframe.gender, DOB=dbframe.DOB,salary=dbframe.Salary ) obj.save() return render(request, 'Import_excel_db.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'Import_excel_db.html',{})
Importing data from excel into database using import-export library
from tablib import Dataset from .Resources import EmployeeResource def Import_excel(request): if request.method == 'POST' : Employee =EmployeeResource() dataset = Dataset() new_employee = request.FILES['myfile'] data_import = dataset.load(new_employee.read()) result = EmployeeResource.import_data(dataset,dry_run=True) if not result.has_errors(): EmployeeResource.import_data(dataset,dry_run=False) return render(request, 'Import_excel_db.html',{})
We need to add import_excel_db.urls to project urls.py
Urls.py
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('import_excel_db.urls')), ]
Create urls.py file inside import_exceldb app to write the URL pattern or providing routing for the application.
urls.py
from django.urls import path from . import views from Import_Excel import settings from django.conf.urls.static import static urlpatterns =[ path("",views.Import_Excel_pandas,name="Import_Excel_pandas"), path('Import_Excel_pandas/', views.Import_Excel_pandas,name="Import_Excel_pandas"), path('Import_excel',views.Import_excel,name="Import_excel"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
import os STATIC_ROOT = os.path.join(BASE_DIR, "assets")
Create a template folder inside import_exceldb app and create html file in the directory.
import_excel_db.html
{% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-6 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Import Excel Data into Database</h2> <div class="clearfix"></div> </div> <div class="x_content"> <div class="col-md-8 col-sm-12 col-xs-12 form-group"> </div> <input type="file" name="myfile" class="form-control"> <button type="submit" class="btn btn-success" >Upload data using Pandas</button> <button type="submit" class="btn btn-success" >Upload data using Import_Export_Lib</button> </div> </div> </div> </div> </form> {% endblock %}
Now make migrations Python manage.py makemigrations Python manage.py migrate Python manage.py runserver
The post Import Data from Excel into Database using Django appeared first on Tech Insights.
]]>The post Execute the CRUD Operation in Django with SQLite Database appeared first on Tech Insights.
]]>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
The post Execute the CRUD Operation in Django with SQLite Database appeared first on Tech Insights.
]]>