CRUD Generic Class-Based Views Django.How

Author avatar wrote on 02/06/2022

1 models.py


from django.contrib.gis.db import models

class  Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    address = models.CharField(max_length=100)
    phone = models.CharField(max_length=50)


2 admin.py


from django.contrib import admin 
from .models import Contact
admin.site.register(Contact)

3 views.py


from django.views.generic import ListView, DetailView 
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Contact

class ContactList(ListView): 
    model = Contact

class ContactDetail(DetailView): 
    model = Contact

class ContactCreate(CreateView): 
    model = Contact
    success_url = reverse_lazy('contact_list')
    success_message = "contact successfully created!"

class ContactUpdate(UpdateView): 
    model = Contact
    success_url = reverse_lazy('contact_list')
    success_message = "contact successfully created!"

class ContactDelete(DeleteView): 
    model = Contact
    success_url = reverse_lazy('contact_list')
    success_message = "contact successfully created!"

4 Templates

contact_list.html

contact_details.html

contact_form.html

contact_confirm_delete.html

5 urls.py


from django.urls import path
from . import views

urlpatterns = [
    # [...]
    path('contacts', views.ContactList.as_view(), name='contact_list'),
    path('contact/', views.ContactDetail.as_view(), name='contact_detail'),
    path('create', views.ContactCreate.as_view(), name='contact_create'),
    path('update/', views.ContactUpdate.as_view(), name='contact_update'),
    path('delete/', views.ContactDelete.as_view(), name='contact_delete'),
]

Passing extra context in views


def get_context_data(self, *args, **kwargs):          
    context = super(CBV_NAME, self).get_context_data(*args, **kwargs)
    new_context_entry = "here it goes"
    context["new_context_entry"] = new_context_entry
    return context

# or
  self.extra_context["another_one"] = "here goes more"

Resources
  • https://www.techiediaries.com/django-crud-generic-views
  • https://github.com/digenaldo/django-crud-example
  • https://www.geeksforgeeks.org/class-based-generic-views-django-create-retrieve-update-delete
  • CRUDgen Django CRUD generator