Django Class Based Add, Delete, Update And Select Example

In the process of writing websites, we often need to implement some basic functions, such as add, delete, update and select data. Python Django encapsulates all these complex logic things into methods for us to use it directly. The experience in the process of using them is simple enough. This article will show you some examples.

1. Create Many-To-One Relationships Class Model.

We all know that one company has multiple employees, now we create two class one is Company the other is Employee and we associate them with a many-to-one foreign key field as following.


from django.db import models
from django.shortcuts import reverse

class Company(models.Model):
    text = models.CharField('company', max_length=100)
    date_added = models.DateTimeField('date_added', auto_now_add=True)

    class Meta:
        ordering = ['-date_added']
        verbose_name_plural = "Company"

    def __str__(self):
        return self.text

class Employee(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Company")
    text = models.TextField('company_employee')
    date_added = models.DateTimeField('date_added', auto_now_add=True)

    class Meta:
        ordering = ['-date_added']
        verbose_name_plural = "company's employee name"

    def __str__(self):
        return self.text[:50] + "..."

2. Process Model Data In Views.

2.1 In views, we use the ListView and DetailView provided by Django for data query processing.


# General display view
from django.views.generic import ListView, DetailView  

# General edit view include add, delete and update.
from django.views.generic.edit import CreateView, DeleteView, UpdateView   
from . import models as md

# The jump link method after successful add, delete and update.
from django.urls import  reverse_lazy  

# ListView that display companies query list.
class CompaniesList(ListView):
    # Belong's to which model.
    model = md.Company  

    # Specify the static display template file.
    template_name = 'mysite/companies.html'   
    # Custom defined context object value, this can override default context object value.
    context_object_name = 'companies'  

# DetailView used to display the company's employee info.
class CompanyDetail(DetailView):
    model = md.Company
    template_name = 'mysite/company.html'

2.2 Use Django CreateView, DeleteView and UpdateView to process form data.

In the process of add, delete, update and select, we use the Django provided CreateView (add), UpdateView (update), DeleteView (delete) to process the form data.


class CompanyUpdate(UpdateView):
    # Define which model this view belongs to.
    model = md.Company  
    # Use our custom view template to override the default view template.
    template_name = 'mysite/edit_company.html'    
    # Allow edit fields.
    fields = ['name']   
    # Jump link after successfull update.
    success_url = reverse_lazy('mysite:companies')    

class CompanyDelete(DeleteView):
    model = md.Company
    template_name = 'mysite/del_company.html'
    success_url = reverse_lazy('mysite:companies')

class EmployeeCreate(CreateView):
    model = md.Employee
    template_name = 'mysite/new_employee.html'
    fields = ['company', 'name']
    success_url = reverse_lazy('mysite:companies')

2.3 Define links in our

Note that the file here is in our application, not in the project. We use include to distribute urls in the project.


from django.urls import path
from . import views
from .views import CompanyCreate, CompanyUpdate, CompanyDelete, EmployeeCreate

app_name = 'mysite'
urlpatterns = [
    path('companies/', views.CompaniesList.as_view(), name='companies'),
    path('companies/<int:pk>/', views.CompanyDetail.as_view(), name='company'),
    path('company/add/', CompanyCreate.as_view(), name='company-add'),
    path('company/<int:pk>/', CompanyUpdate.as_view(), name='company-update'),
    path('company/<int:pk>/delete/', CompanyDelete.as_view(), name='company-delete'),

    path('employee/add/', EmployeeCreate.as_view(), name='employee-add'),

2.4 Company and employee template html file.

<!-- companies.html : list company data. -->

<a href="{% url 'mysite:company-add' %}">Add Company</a>
    {% if companies %}
        {% for company in companies %}
          <li><a href="{% url 'mysite:company' %}" >{{ }}</a> </li>
              <a href="{% url 'mysite:company-update' %}">Update</a>
            <a href="{% url 'mysite:company-delete' %}">Delete</a>
        {% endfor %}
        {% else %}
            <p>There is no company info.</p>
    {% endif %}

<!-- new_company.html -->

<form action="{% url 'mysite:company-add' %}" method="post">
        {% csrf_token %}
       {{ form }}
   <input type="submit" class="btn btn-block" value="Submit">
<!-- employee.html : list employee data. -->

<a href="{% url 'mysite:employee-add' %}">Add Employee</a>
    <h1>{{ company }}</h1>

    {% for employee in topic.employee_set.all %}
        {{ }}
       <p>Date:{{ employee.date_added }}</p>
    {% endfor %}