Django Python Archives - Tech Insights https://reactconf.org/category/django/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Mon, 08 May 2023 03:08:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 Django Python Archives - Tech Insights https://reactconf.org/category/django/ 32 32 230003556 Django Session | How to Create a Session in Django Python https://reactconf.org/django-session-create/ https://reactconf.org/django-session-create/#respond Mon, 08 May 2023 03:08:25 +0000 https://labpys.com/?p=1250 In this article, we will discuss How to Create a Session in Django Python, and their role in securing web applications. Sessions provide similar functionality as cookies but are more …

The post Django Session | How to Create a Session in Django Python appeared first on Tech Insights.

]]>
In this article, we will discuss How to Create a Session in Django Python, and their role in securing web applications. Sessions provide similar functionality as cookies but are more secure because they store data on the server side rather than on the client side. This article will cover how to set up Django sessions and demonstrate how to use them in a simple web application.

Session in Django

With the session framework in Django, you can save and retrieve any data on a per-visitor basis for your website. This framework stores the data on the server side and handles the sending and receiving of cookies in a simplified way. Essentially, the cookie only contains a session ID rather than the actual data, unless you’re using the cookie-based backend.

Enabling Sessions in Django

We must first enable session middleware in our application before we can create a session in Django. The session middleware is responsible for handling sessions. Middleware is a mechanism to add functionality to Django’s request/response processing pipeline.

To enable session middleware, we need to add the following line to our MIDDLEWARE setting in settings.py:

INSTALLED_APPS = [   
    'django.contrib.sessions',
]

MIDDLEWARE = [
        'django.contrib.sessions.middleware.SessionMiddleware',
      
]

More Related Articles Find Duplicate Records in Django ORM

Create Session in Django

Creating a session in Django is simple. To save data in the user’s session, we can store the request.session object. Here’s an example.

def setSession(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')         
                  
    try:                      
        user = authentication.objects.get(username=username,password=password)            
        if user is not None:
            request.session['username'] = user.username
            request.session['emailid'] = user.emailid 
            request.session['userid'] = user.id
            render(request, 'index.html', {})    
    except Exception as identifier:
            
            messages.error(request, "Invalid login details given")   
            return redirect('/')    

Get Django Session Data

In Django, we can simply read from the request.session object to retrieve session data. Here’s an example:

def getSession(request):
    if 'User_id' in request.session:
        username = request.session['username']   

Delete a Django Session Value

It is important to note that reading from the session does not remove the data from the session. We can use the del keyword to erase data from the session, as shown below.

def logout(request):
    del request.session['User_id']
    return redirect('/')

Conclusion
We’ve covered the fundamentals of session creation in Django Python in this article. We began by talking about what sessions are and how they function in Django. Then we went through how to create and store data in sessions, as well as how to retrieve and delete data from them.

The post Django Session | How to Create a Session in Django Python appeared first on Tech Insights.

]]>
https://reactconf.org/django-session-create/feed/ 0 1250
How to Find Duplicate Records in Django ORM https://reactconf.org/how-to-find-duplicate-records-in-django-orm/ https://reactconf.org/how-to-find-duplicate-records-in-django-orm/#respond Fri, 21 Apr 2023 02:46:03 +0000 https://labpys.com/?p=1112 Are duplicate records a problem for your Django ORM? it’s common problem, but fortunately, there are a number of techniques to locate and get rid of them. In this article, …

The post How to Find Duplicate Records in Django ORM appeared first on Tech Insights.

]]>
Are duplicate records a problem for your Django ORM? it’s common problem, but fortunately, there are a number of techniques to locate and get rid of them. In this article, we will learn How to Find Duplicate Records in Django ORM. We explore various approaches for identifying and handling duplicates in Django ORM.

Why Do Multiple Records Exist?

Multiple problems with your application can arise from duplicate records. First, they can confuse your users by showing them many entries for what they once believed to be a single item. Additionally, this may make it challenging to manage data and produce reliable reports. Additionally, since duplicate records occupy unneeded space in your database, they can affect speed.

Find Duplicate Records Using Django ORM

Fortunately, Django ORM has a number of methods for locating and eliminating duplicate data. Let’s look at some of the methods you have at your disposal.

Find Duplicate Records in a Single Field

Using the values() and annotate() methods to group records by a single field and count the number of records in each group is one technique to check for duplicates. For instance, if your Users model has a username field, you can use the following code to discover duplicate usernames.

#Checking Duplicate Record in Signle Field
@api_view(['GET',])
def GetduplicateUsers(request):
    if request.method == 'GET':
        getusers = authentication.objects.values('username','password').annotate(username_count=Count('username')).filter(username_count__gt=1)
        serializer = serialize(getusers, many=True)        
        return Response(serializer.data)

This code counts the number of records in each group of Users records and sorts them according to username . When there are duplicate records, the filter() method only returns the groups that have more than one record.

Finding Duplicates in Multiple Fields

Use the Q object and distinct() function to search for duplicate records across several fields. For instance, the following code may be used to discover duplicate records based on all two columns in a Users model with username and email fields:

#Checking Duplicate Record in multiple Field
@api_view(['GET',])
def GetduplicatemultipleUsers(request):
    if request.method == 'GET':
        getusers = authentication.objects.filter(Q(username__in=authentication.objects.values('username').annotate(count=Count('id')).filter(count__gt=1).values('username')) & Q(emailid__in=authentication.objects.values('emailid').annotate(count=Count('id')).filter(count__gt=1).values('emailid'))).distinct()
        serializer = serialize(getusers, many=True)        
        return Response(serializer.data)
Document

The Q object is used in this code to filter Users’ records based on various fields. Records are grouped by each field using the values() and annotate() methods, and the number of records in each group is counted. Then, only the groups with multiple records, indicating that there are duplicates, are returned using the filter() method. Any duplicates are eliminated from the final query result using the distinct() technique.

Conclusion

In Django ORM, duplicate records can be an irritating and time-consuming issue. But with the methods described in this article, you may easily find and get rid of duplicates from your database. To maintain correct and clean data, keep in mind to periodically check for duplication.

The post How to Find Duplicate Records in Django ORM appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-find-duplicate-records-in-django-orm/feed/ 0 1112
How to Create CRUD API in Django Rest Framework https://reactconf.org/how-to-create-crud-api-in-django-rest-framework/ https://reactconf.org/how-to-create-crud-api-in-django-rest-framework/#respond Tue, 18 Apr 2023 02:45:06 +0000 https://labpys.com/?p=1081 Web development has become a crucial component of enterprises in the modern world. To build an effective web application, we need to create a robust API. The Django Rest Framework …

The post How to Create CRUD API in Django Rest Framework appeared first on Tech Insights.

]]>
Web development has become a crucial component of enterprises in the modern world. To build an effective web application, we need to create a robust API.

The Django Rest Framework (DRF) is a powerful tool to create CRUD API in the Django web framework, which is based on python

In this post, we will look at how to create CRUD API in the Django Rest Framework. Create, Retrieve, Update, and Delete are the four fundamental activities you may do using a CRUD API. To interface with a database, web applications frequently use these operations.

Also, Check the Previous Article Implement Join Operations in Django ORM

Django CRUD (Create, Read, Update, Delete) Operation

Before we start building the CRUD API, we need to install Django and  Django Rest Framework. The steps are as follows.

Setting Django Rest Framework

Install Django and Rest Framework

Pip install Django
Pip install djangorestframework

Create a new Django Project

Django-admin startproject CRUD_API_Restframework

Create a new App

Python manage.py startapp CRUD_API

Configure the Settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CRUD_API',
    'rest_framework',
]

Create Django Models

Now we need to create a Models in our app. The model will define the structure of data.

from django.db import models

# Create your models here.


class authentication(models.Model):    
        username = models.CharField(max_length=100)
        password = models.CharField(max_length=100)
        emailid = models.CharField(max_length=100,default=True)
        is_active = models.IntegerField()
        firstname = models.CharField(max_length=100,default=True)
        lastname = models.CharField(max_length=100,default=True)
        address = models.CharField(max_length=100,default=True)
        contactno = models.CharField(max_length=100,default=True)
        gender = models.CharField(max_length=100,default=True)        
        
        def __str__(self):
            return self.username

Migration

Python manage.py makemigrations
Python manage.py migrate

Create Serializers

Serializers create a format for complicated data types, like Python objects, so that it may be quickly translated into JSON or XML content. Models in DRF are transformed into JSON, XML, or other content types using serializers.

from rest_framework import serializers
from .models import authentication


class serialize(serializers.ModelSerializer):
    class Meta:
        model = authentication
        fields =['id','username','password','emailid']


class messagserializer(serializers.Serializer):
  Response = serializers.CharField()
  Message = serializers.CharField()

Create a Views

The API’s fundamental component views, respond to queries, process data, and handle incoming request. Django Rest Framework has a number of views that can be customized to support CRUD activities

from django.shortcuts import get_object_or_404, redirect, render
from django.template.response import TemplateResponse
from django.http import HttpResponse,HttpRequest
from rest_framework import serializers,status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.urls import reverse
from django.contrib import messages 
from django.contrib.auth import authenticate
from .models import authentication
from .Serializers import serialize,messagserializer
import json
import requests
 
# Create your views here.


@api_view(['GET',])
def getusers(request):
    if request.method == 'GET':
        getusers = authentication.objects.all()
        serializer = serialize(getusers, many=True)
        request.session['users'] = serializer.data
        return Response(serializer.data)


@api_view(['GET'])
def getusersid(request):

    
    if request.method == 'GET':
        argdata = request.data
        getuserss = authentication.objects.filter(username=argdata['username'] , password=argdata['password'])
        serializer = serialize(getuserss, many=True)
        request.session['users'] =serializer.data
        return Response(serializer.data)
    
    return Response('Failure')


@api_view(['POST',])
def postusers(request, *args, **kwargs):
    argdata = request.data
   
    if request.method == 'POST':
        argdata = request.data
        isvalid = authentication.objects.filter(username=argdata['username']).exists()
        if isvalid==False:
            postusers = authentication.objects.create(username=argdata['username'],password=argdata['password'],emailid=argdata['emailid'],is_active=1)
            postusers.save()
            getuserss = authentication.objects.filter(username=argdata['username'])
            serializer = serialize(getuserss, many=True) 
            context = {"getdata":serializer.data,"response":"Success"}               
            return Response(context)
        else:
            context = [{"Response":'User Already Registered',"Message":'403'}]
                
            serializer = messagserializer(context, many=True) 
            return Response(serializer.data)
   


@api_view(['PUT','GET'])
def Editusers(request, *args, **kwargs):
    
    
    if request.method == 'PUT':
        user_instance =  authentication.objects.get(username=request.data.get('username')) #self.get_object(id,request.data.id)
        if not user_instance:
            return Response({"message":'User Not Registered'},status=status.HTTP_404_NOT_FOUND)
        data = {
            'username': request.data.get('username'),
            'password': request.data.get('password'),
            'emailid': request.data.get('emailid'),
            'is_active': request.data.get('is_active')        
        }
        serializer = serialize(instance=user_instance, data=data,partial=True)
        if serializer.is_valid():
            serializer.save()
            context = {"getdata":serializer.data,"response":"Success"}               
            return Response(context)
    return Response(serializer._errors,status=status.HTTP_400_BAD_REQUEST)
   
@api_view(['DELETE'])
def Delete_User(request):
    argdata = request.data
    isvalid = authentication.objects.filter(username=argdata['username']).exists()
         
    if isvalid==True:
        users = get_object_or_404(authentication,username=argdata['username'])
        users.delete()
        context = {"response":"Success"}               
        return Response(context)
    else:
        context = [{"Response":'User Not Registered',"Message":'403'}]
        return Response(context)
 
 

Create URLS

We need to map the views to URLs to make them accessible through the API. Here are the steps to follow.

  • Create a new file urls.py in the CRUD_API directory

Configure the URLs for the views

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

urlpatterns = [    
        
    path('getusers/',views.getusers, name="getusers"),
    path('getusersid/',views.getusersid, name="GetUseById"),
    path('Addusers/',views.postusers, name="postusers"),
    path('Editusers/',views.Editusers, name="Editusers"),
    path('Delete_User/',views.Delete_User, name="Delete_User"),
]

Include the app Urls in the project URLs

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('CRUD_API.urls')),
]

Start the Django Development Server

Python manage.py runserver

Testing the API using POSTMAN

Here can test the API using the POSTMAN tool.

Create User

Get All Users

Get By Id

Update User

Delete User

The post How to Create CRUD API in Django Rest Framework appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-crud-api-in-django-rest-framework/feed/ 0 1081
How to Implement Join Operations in Django ORM https://reactconf.org/how-to-implement-join-operations-in-django-orm/ https://reactconf.org/how-to-implement-join-operations-in-django-orm/#respond Mon, 17 Apr 2023 01:43:29 +0000 https://labpys.com/?p=1061 You will probably need to work with a database at some point if you are using Django to create a web application.  Django Object Relational Mapping(ORM), makes this process easier …

The post How to Implement Join Operations in Django ORM appeared first on Tech Insights.

]]>
You will probably need to work with a database at some point if you are using Django to create a web application. 

Django Object Relational Mapping(ORM), makes this process easier by allowing you to work with Python classes instead of SQL queries.

Joining two or more tables to extract relevant data is one of the most common tasks when working with a database. We will look into joining tables with Django ORM in this tutorial.

Database Relationships

Before we dig into joining tables, it is essential to understand the different types of relationships that can exist between tables in a database. The three most common types of relationships are.

  • One-to-one(1:1)  – Each record in one table is related to one and only one record in another table.
  • One-to-many(1:N) – Each record in one table is related to zero, one, or many records in another table.
  • Many-to-Many(N: N) – Each record in one table is related to zero, one, or many records in another table and vice versa.

Create Django Join

Create a Project

First, we need to create a project by running the following commands in your terminal or command prompt

Django-admin startproject Joins_ORM

Create an app

A Django project consists of one or more apps. Creating a new app by running the following command in your terminal or command prompt

Python manage.py startapp jointable

Create a Model

from django.db import models

# Create your models here.

class Author(models.Model):
    FirstName = models.CharField(max_length=100)
    LastName = models.CharField(max_length=100)
    MiddleName = models.CharField(max_length=100)

class Books(models.Model):
    title = models.CharField(max_length=200)
    total_page = models.IntegerField()
    auth_id = models.ForeignKey(Author, on_delete=models. CASCADE)
    

Django Join Tables Using ORM

INNER JOIN

from django.shortcuts import render
from .models import Books,Author

# Create your views here.

def jointable(request):
    books = Books.objects.select_related('auth_id').filter(title='A Better World')

    return render(request,'index.html',{'context':books})

LEFT JOIN

def Leftjoin(request):

    books = Books.objects.filter(Q(auth_id__isnull=True)|Q(auth_id__isnull=False))   
    return render(request,'index.html',{'context':books})

RIGHT JOIN

def Rightjoin(request):

    books = Books.objects.select_related('auth_id').all()

    return render(request,'index.html',{'context':books})

See More How to Add Pagination

The post How to Implement Join Operations in Django ORM appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-implement-join-operations-in-django-orm/feed/ 0 1061
How to Add Pagination in Django Python https://reactconf.org/how-to-add-pagination-in-django-python/ https://reactconf.org/how-to-add-pagination-in-django-python/#respond Tue, 30 Aug 2022 16:20:00 +0000 https://labpys.com/?p=435 In this tutorial we will discuss How to Add Pagination in Django Python Web application. What is Pagination – Pagination is the process of distributing a website’s content across multiple …

The post How to Add Pagination in Django Python appeared first on Tech Insights.

]]>
In this tutorial we will discuss How to Add Pagination in Django Python Web application.

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.

]]>
https://reactconf.org/how-to-add-pagination-in-django-python/feed/ 0 435
How to Create Cascading/Dependent Dropdown List in Django Python https://reactconf.org/how-to-create-cascading-dependent-dropdown-list-in-django-python/ https://reactconf.org/how-to-create-cascading-dependent-dropdown-list-in-django-python/#comments Fri, 05 Nov 2021 07:01:23 +0000 https://labpys.com/?p=397 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 …

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.

Create a Django Dropdown project 

                We need to create a Django project  dropdownfill

               Django-admin startproject dropdownfill

Create Django App

                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

                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',
]

Create the Model

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) 

Create the views functions

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/

Provide Routing (URL patterns)

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 Template

            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.

]]>
https://reactconf.org/how-to-create-cascading-dependent-dropdown-list-in-django-python/feed/ 1 397
How to Generate QR Code Using Django https://reactconf.org/how-to-generate-qr-code-using-python/ https://reactconf.org/how-to-generate-qr-code-using-python/#respond Thu, 02 Sep 2021 12:10:00 +0000 http://labpys.com/?p=233 In this article, we will learn how generate a QR code using Django python. Here we generate QR code images from any text. First, we need to install the following …

The post How to Generate QR Code Using Django appeared first on Tech Insights.

]]>
In this article, we will learn how generate a QR code using Django python. Here we generate QR code images from any text.

First, we need to install the following packages

Step-1

  1. pip install qrcode

Step-2

  1. create django project
  2. create django app

then include the app in the settings.py file

Create views.py





from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect 
import io   
import qrcode.image.svg 
import qrcode
  
def qr_code(request): 
    context ={}
    if request.method == "POST":
        factory = qrcode.image.svg.SvgImage
        qr_image = qrcode.make(request.POST.get("http://labpys.com",""),image_factory=factory, box_size=20)    
        bufstore = io.BytesIO()
        qr_image.save(bufstore)    
        context["svg"] = bufstore.getvalue().decode()   
    return render(request,'qrcode.html',context=context)
https://labpys.com/how-to-execute-the-crud-operation-in-django/
Now to set url in urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("qr_code.urls")),
]
 



from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
   path("",views.qr_code,name="qrcode"),
]

then Create Template folder in that create HTML file qrcode.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>QR Code Generator</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">  
 
</head>
<body>
  <div class="row col-sm-6 shadow">
    <form method="post">
      {% csrf_token %}
      <h3>generate a QR code(Enter Any text)</h3>
      <div class="row-group">         
        <input type="text"  class="form-control" name="qr_text" autofocus>
      
      <br/>
      <div class="row-group">
        <input type="submit" style="max-width: 200px; margin: auto" class="form-control">
      </div>
      <br/>
    </div>
    </form>
      <div class="row-group">
        <div style="margin: auto">
          {{ svg|safe }}
        </div>
      </div>
  </div>
</body>
</html>

Thank you for reading.

The post How to Generate QR Code Using Django appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-generate-qr-code-using-python/feed/ 0 318
How to create Dynamic menu from Database using Django Python https://reactconf.org/how-to-create-dynamic-menu-from-database-using-django-python/ https://reactconf.org/how-to-create-dynamic-menu-from-database-using-django-python/#comments Wed, 07 Jul 2021 17:02:00 +0000 http://labpys.com/?p=332 In this article, we will learn how to create a dynamic menu from Database using Django Python. Dynamic menus are very useful when you set access permission to users or …

The post How to create Dynamic menu from Database using Django Python appeared first on Tech Insights.

]]>
In this article, we will learn how to create a dynamic menu from Database using Django Python. Dynamic menus are very useful when you set access permission to users or restrict some pages to particular users at runtime.

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.

]]>
https://reactconf.org/how-to-create-dynamic-menu-from-database-using-django-python/feed/ 3 332
How to Upload Files in Django Python https://reactconf.org/how-to-upload-files-images-in-django-python/ https://reactconf.org/how-to-upload-files-images-in-django-python/#respond Sun, 27 Jun 2021 08:32:29 +0000 http://labpys.com/?p=308 In this tutorial, we will learn how to upload media files such as images, files, etc. It is generally the most common requirement in any modern web application is the …

The post How to Upload Files in Django Python appeared first on Tech Insights.

]]>
In this tutorial, we will learn how to upload media files such as images, files, etc.

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.
http://labpys.com/how-to-execute-the-crud-operation-in-django/

Django File Upload

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.

]]>
https://reactconf.org/how-to-upload-files-images-in-django-python/feed/ 0 322
How to Export Data from the Database into Excel using Django Python https://reactconf.org/export-data-from-database-into-excel-using-django/ https://reactconf.org/export-data-from-database-into-excel-using-django/#respond Mon, 18 Jan 2021 15:45:44 +0000 http://labpys.com/?p=274 In this tutorial, we will learn how to Export Data from the Database into Excel using Django. In this Django application, I used the pandas library. Let’s start Install  pandas …

The post How to Export Data from the Database into Excel using Django Python appeared first on Tech Insights.

]]>
In this tutorial, we will learn how to Export Data from the Database into Excel using Django. In this Django application, I used the pandas library.

Let’s start

Install  pandas library

First, create a Django project, then create models

Django Export Data From Database into Excel

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.

]]>
https://reactconf.org/export-data-from-database-into-excel-using-django/feed/ 0 321