Django CRUD( Create, read, update and delete) with ModelForm

Open Command Prompt in Windows 

then in command prompt  type    d:  

and press enter .

and use following commands 

To create folder  myap -execute the following command:

D:\> mkdir myap

To  go  myap folder path -execute the following command:

D:\>cd myap 

To create a virtual environment for your project, open a new command prompt, navigate to the myap  folder where you want to create your project and then execute the following command:-

D:\myap>python -m venv env

In the command prompt, ensure your virtual environment is active, and execute the following command:

D:\myap>env\Scripts\activate

execute the following command to install django.

D:myap>pip install django

run the following command - This will create a my_project  directory in your current directory

D:\myap>django-admin startproject  my_project

then go to myproject folder path type following command :-


D:\myap>cd my_project


To create your app, make sure you’re in the your project  directory &  type this command:


D:\myap\my_proejct>python manage.py  startapp hello 

That’ll create a directory hello app folder inside my_project folder:-

after it open your myap folder inside it you will see my_project folder 



and inside my_project folder you will see following structure:-

 


Now start step by step code for this open your project folder in  visual code :- 



step 1:- write  urls.py  file code in your Project folder  which my_project :-

from django.contrib import admin



from django.urls import path, include





urlpatterns=[

   

path('hello/',include('hello.urls')),

path('admin/', admin.site.urls),

]

step 2:- write code models.py file under your hello app folder hello:-


from django.db import models

# Create your models here.

class ContactForm(models.Model):
       

    fullname= models.CharField(max_length=100)
    email= models.EmailField()
    contact= models.CharField(max_length=50)
    message= models.CharField(max_length=200)
   


and  command   python manage.py makemigrations

or

py manage.py makemigrations


after it run

python manage.py migrate

or 

py manage.py migrate



and write code admin.py file in your hello app folder :-

from django.contrib import admin
from .models import ContactForm

# Register your models here.

admin.site.register(ContactForm)

step 3:- write code for forms.py file under your hello app folder :-


from django import forms
from .models import ContactForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class FormContactForm(forms.ModelForm):
    class Meta:
        model= ContactForm
        fields= ["fullname", "email", "contact", "message"]

class NewUserForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ["username", "email", "password1", "password2"]

step 4:- write code for urls.py file in hello app folder :-


from django.urls import path

from .import views



urlpatterns=[
path('',views.index,name='index'),
path('home/',views.home,name='home'),
path('homepage/',views.homepage,name='homepage'),
path('about/',views.about,name='about'),

path('showform/', views.showform),
path('search/', views.search,name='search'),
path('search1/', views.search1,name='search1'),


path('editemp/<int:id>', views.editemp, name='editemp'),
path('updateemp/<str:id>', views.updateemp, name='updateemp'),


     path("register", views.register_request, name="register"),
         path("login", views.login_request, name="login"),
         path("logout", views.logout_request, name= "logout"),









]


step 5:- write code for views.py file in your hello app folder :-


from urllib import request
from django.shortcuts import render,redirect
from  hello.models  import ContactForm,contactEnquiry
from  hello.forms import FormContactForm
from .forms import NewUserForm

from django.http import HttpResponse
from django.contrib.auth import login, authenticate,logout #add this
from django.contrib import messages

from django.contrib.auth.forms import AuthenticationForm
from django.db.models  import Q


def index(request):
   
    data="50"
   
    request.session['paid']=data
 

    return render(request, "home.html",{'data':data})

def home(request):
    data='5000'
   
   
    print(request.session['paid'])
    return render(request, "home.html",{'data':data})

def about(request):

    data=request.session.get('paid')

    return render(request, "about.html",{'data':data})

def homepage(request):

   
    return render(request, "homepage.html")





def showform(request):
    form= FormContactForm(request.POST or None)
    if form.is_valid():
        form.save()
 
    context= {'form': form }
       
    return render(request, 'contactform.html', context)





def home(request):
 serviceData=ContactForm.objects.all()
 data={'serviceData':serviceData
        }


 return render(request,"home.html",data)

def  editemp(request,id):
 data=ContactForm.objects.get(id=id)
 return render(request, "edit.html",{'editupdaterecord':data})


def  updateemp(request,id):
 if request.method=='POST':
  pi=ContactForm.objects.get(id=id)
  form= FormContactForm(request.POST ,instance=pi)
 if form.is_valid():
       
        form.save()
 msg="record updated"
 return render(request, "update.html",{'editupdaterecord':msg})
     

def search(request):
    if request.GET.get('myform'): # write your form name here      
        book_name =  request.GET.get('myform')  
           
        try:
               
            status = ContactForm.objects.filter(fullname__icontains=book_name)
            return render(request,"search1.html",{"books":status})
        except:
            return render(request,"search1.html",{'books':status})
    else:
        return render(request, 'search1.html', {'books':status})


def search1(request):
 if 'q'  in request.GET:
    q=request.GET['q']
    multiple_q=Q(Q(fullname=q)| Q(message=q))
    data=ContactForm.objects.filter(multiple_q)
   
 else:
    data =ContactForm.objects.all()
   
 return render(request,'search1.html',{
 'data':data
 })

 

def login_request(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.info(request, f"You are now logged in as {username}.")
                return redirect("homepage")
            else:
                messages.error(request,"Invalid username or password.")
        else:
            messages.error(request,"Invalid username or password.")
    form = AuthenticationForm()
    return render(request, 'login.html', context={"login_form":form})

def register_request(request):
    if request.method == "POST":
        form = NewUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, "Registration successful." )
            return redirect("home")
        messages.error(request, "Unsuccessful registration. Invalid information.")
    form = NewUserForm()
    return render (request, 'register.html', context={"register_form":form})

def logout_request(request):
    logout(request)
    messages.info(request, "You have successfully logged out.")
    return redirect("homepage")


step 6:- write code for contactform.html file  under templates folder inside your hello app folder  :-

<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>Django Contact Form</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.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>  
<body>  
<form method="POST" class="post-form" action="#">  
{% csrf_token %}  
<div class="container">  
<div class="form-group">
    <label for="id" class="control-label col-sm-2">id</label>
    <div class="col-sm-10">
    <input type="text" name="id" value="" class="form-control" />
    </div>
    <label for="fullname" class="control-label col-sm-2">Full Name</label>
    <div class="col-sm-10">
    <input type="text" name="fullname" value="" class="form-control" />
    </div>
</div>
<div class="form-group">
    <label for="email" class="control-label col-sm-2">Email</label>
    <div class="col-sm-10">
    <input type="text" name="email" value="" class="form-control" />
    </div>
</div>
<div class="form-group">
    <label for="contact" class="control-label col-sm-2">Contact</label>
    <div class="col-sm-10">
    <input type="text" name="contact" value="" class="form-control" />
    </div>
</div>
<div class="form-group">
    <label for="message" class="control-label col-sm-2">Message</label>
    <div class="col-sm-10">
    <input type="text" name="message" value=""/>
    </div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>  
</body>  
</html>

step 7:- home.html file code under templates folder :-

<html>
    <head>
        {% load static %}

        <link rel="stylesheet" href="{% static 'ok.css' %}">


    </head>
    <body>
       
       
        <h1 class="myclass">hello world how are you
            {{data}}
        </h1>
        <div>

            {% for n in serviceData %}
           
            {{n.id}}
           
            <span class="{{n.fullname}}"> {{n.fullname}}</span>
           
            <span class="{{n.email}}">{{n.email}} </span>
           
           
           
            <p> {{n.contact}} </p>
           
            <a href="{% url 'editemp' n.id %}">Edit</a>


          {% endfor %}  
          </div>
    </body>
</html>

step 8:- 

write code for edit.html file under templates folder :-

{{id}}



<form  action="{% url 'updateemp' editupdaterecord.id %}"  method="post">

    {% csrf_token %}
   
    name <input type=text name="fullname" value={{editupdaterecord.fullname}}>
   
     email <input type=text name="email" value={{editupdaterecord.email}}>
     Contact <input type=text  name="contact" value={{editupdaterecord.contact}}>
     message <input type=text name="message" value={{editupdaterecord.message}}>
   
     <input type=submit value=update>
   
     </form>
     

step 9:- about.html file code :-


<html>
    <head>

    </head>
    <body>
        <p>about page</p>
        <p>{{data}} </p>
   
    </body>
</html>

step 10:- homepage.html file code under templates folder:-


<!--Navbar-->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="False" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarText">
      <ul class="navbar-nav mr-auto">
        {% if user.is_authenticated %}
       
        <li class="nav-item">
          <a class="nav-link" href="{% url 'logout' %}">Logout</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Welcome, {{user.username}}</a>
        </li>
 
        {% else %}
 
        <li class="nav-item">
          <a class="nav-link" href="{% url 'login' %}">Login</a>
        </li>
 
        {% endif %}
      </ul>
    </div>
  </nav>


step 11:- Run  your project  with command :-

py manage.py runserver




after click on Edit  you will see following output:-

Make Changes Value and click on update.


then  you will see output:-





Previous
Next Post »