Setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangodb',
'USER':'root',
'PASSWORD':'mysql',
'HOST':'localhost',
'PORT':'3306'
}
}
Create a model
from django.db import models
class Employee(models.Model):
eid = models.CharField(max_length=20)
ename = models.CharField(max_length=100)
eemail = models.EmailField()
econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"
Create a modelform
rom django import forms
from employee.models import Employee
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = "all"
Views Function
from django.shortcuts import render, redirect
from employee.forms import EmployeeForm
from employee.models import Employee
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
employee = Employee.objects.get(id=id)
employee.delete()
return redirect("/show")
Routing Url
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/int:id', views.edit),
path('update/int:id', views.update),
path('delete/int:id', views.destroy),
]