Complete Django/MySQL CRUD Operations

Learned from CodAffection online course, code has been staged on github:
https://github.com/zhuby1973/python/tree/master/employee_project

we need pip install django-crispy-forms for this project.
1. django-admin startproject employee_project
2. python manage.py runserver
3. python manage.py startapp employee_register
edit settings.py, urls.py, views.py and models.py, then run migrate command to create tables:
python manage.py migrate
python manage.py makemigrations employee_register
python manage.py sqlmigrate employee_register 0001
python manage.py sqlmigrate employee_register 0002
python manage.py migrate
python manage.py createsuperuser (create admin user and verify in admin page)
you can verify the tables in MySQL.

# this is employee_register/views.py:
from django.shortcuts import render,redirect
from .forms import EmployeeForm, RegisterForm
from .models import Employee
import os
from django.conf import settings
from django.contrib import messages
#from django.contrib.auth import login, authenticate
#from django.contrib.auth.forms import UserCreationForm

# Create your views here.
def register(request):
    registerForm = RegisterForm(request.POST or None)
    if request.method == "POST":
        if registerForm.is_valid():
            registerForm.is_staff = True
            registerForm.save()

    return render(request, "registration/register.html", {"form": registerForm})

def employee_list(request):
    print (settings.BASE_DIR)
    context = {'employee_list':Employee.objects.all()}
    return render(request,"employee_register/employee_list.html",context)

def employee_form(request, id=0):
    if request.method == "GET":
        if id == 0:
            form = EmployeeForm()
        else:
            employee = Employee.objects.get(id=id)
            form = EmployeeForm(instance=employee)
        return render(request,"employee_register/employee_form.html",{'form':form})
    else:
        if id == 0:
            form = EmployeeForm(request.POST or None, request.FILES or None)
        else:
            employee = Employee.objects.get(id=id)
            employee.image.delete()
            form = EmployeeForm(request.POST or None, request.FILES or None, instance = employee)

        if form.is_valid():
            form.save()
            if id == 0:
                messages.success(request, "Employee Record Added Successfully!")
            else:
                messages.info(request,"Employee Record Updated Successfully!")

        return redirect("/employee/list")


def employee_delete(request,id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    messages.error(request, 'Employee Record Deleted Successfully!')

    return redirect('/employee/list')

Leave a Reply

Your email address will not be published. Required fields are marked *