Solution details

Django simplifies the process of creating CRUD views with a set of four generic class-based views. They can be mapped to their corresponding operations as follows:

  • CreateView: This view displays a blank form to create a new model instance
  • DetailView: This view shows an object's details by reading from the database
  • UpdateView: This view allows you to update an object's details through a prepopulated form
  • DeleteView: This view displays a confirmation page and, on approval, deletes the object from the database

Let's take a look at a simple example. We have a model that contains important dates about events of interest to everyone using our site. We need to build simple CRUD interfaces so that anyone can view and modify these dates. Let's take a look at the ImportantDate model defined in formschapter/models.py as follows:

class ImportantDate(models.Model): 
    date = models.DateField() 
    desc = models.CharField(max_length=100) 
 
    def get_absolute_url(self): 
        return reverse('impdate_detail', args=[str(self.pk)]) 

The get_absolute_url() method is used by the CreateView and UpdateView classes to redirect after a successful object creation or update. It has been routed to the object's DetailView.

The CRUD views themselves are simple enough to be self-explanatory, as shown in the following code within formschapter/views.py:

class ImpDateDetail(generic.DetailView): 
    model = models.ImportantDate 
 
 
class ImpDateCreate(generic.CreateView): 
    model = models.ImportantDate 
    form_class = ImportantDateForm 
 
 
class ImpDateUpdate(generic.UpdateView): 
    model = models.ImportantDate 
    form_class = ImportantDateForm 
 
 
class ImpDateDelete(generic.DeleteView): 
    model = models.ImportantDate 
    success_url = reverse_lazy("formschapter:impdate_list") 

In these generic views, the model class is the only mandatory member to be mentioned. However, in the case of DeleteView, the success_url function needs to be mentioned as well. This is because after deletion, get_absolute_url can no longer be used to find out where to redirect users.

Defining the form_class attribute is not mandatory. If it is omitted, a ModelForm method corresponding to the specified model will be created. However, we would like to create our own model form to take advantage of crispy forms, as shown in the following code in formschapter/forms.py:

from django import forms 
from . import models 
from crispy_forms.helper import FormHelper 
from crispy_forms.layout import Submit

class ImportantDateForm(forms.ModelForm): class Meta: model = models.ImportantDate fields = ["date", "desc"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
        self.helper = FormHelper(self) 
        self.helper.layout.append(Submit('save', 'Save')) 

Thanks to crispy forms, we need very little HTML markup in our templates to build these CRUD forms.

Explicitly mentioning the fields of a ModelForm method is a best practice. Setting fields to '__all__' may be convenient, but can inadvertently expose sensitive data, especially after adding new fields to the model.

The template paths, by default, are based on the view class and the model names. For brevity, we omitted the template source here. Please refer to the templates directory in the formschapter app in the SuperBook project. We use the same form for CreateView and UpdateView.

Finally, we take a look at formschapter/urls.py, where everything is wired up together:

    path('impdates/<int:pk>/', 
         views.ImpDateDetail.as_view(), 
         name="impdate_detail"), 
 
    path('impdates/create/', 
         views.ImpDateCreate.as_view(), 
         name="impdate_create"), 
 
    path('impdates/<int:pk>/edit/', 
         views.ImpDateUpdate.as_view(), 
         name="impdate_update"), 
 
    path('impdates/<int:pk>/delete/', 
         views.ImpDateDelete.as_view(), 
         name="impdate_delete"), 
 
    path('impdates/', 
         views.ImpDateList.as_view(), 
         name="impdate_list"), 
 

Django generic views are a great way to get started with creating CRUD views for your models. With a few lines of code, you get well-tested model forms and views created for you, rather than doing the boring task yourself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.154.70