delete Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Tue, 18 Apr 2023 02:45:06 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 delete Archives - Tech Insights 32 32 230003556 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
Execute the CRUD Operation in Django with SQLite Database https://reactconf.org/how-to-execute-the-crud-operation-in-django/ https://reactconf.org/how-to-execute-the-crud-operation-in-django/#respond Mon, 18 Jan 2021 12:30:14 +0000 http://labpys.com/?p=246 In this tutorial, we will learn how to do CRUD Operations using Django with SQLite Database. In this tutorial, we will Create, Retrieve, Update, and delete records from a database …

The post Execute the CRUD Operation in Django with SQLite Database appeared first on Tech Insights.

]]>
In this tutorial, we will learn how to do CRUD Operations using Django with SQLite Database. In this tutorial, we will Create, Retrieve, Update, and delete records from a database table. So, we will see a step-by-step procedure to do this.

After Creating the Django App let’s create a model that contains table name and fields

http://labpys.com/how-to-create-login-page-using-django-python/

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.

]]>
https://reactconf.org/how-to-execute-the-crud-operation-in-django/feed/ 0 319