Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Class Based vs Function Based Views - Which One is Better to Use in Django?
Next article icon

Class-Based Views (CBVs) allow developers to handle HTTP requests in a structured and reusable way. With CBVs, different HTTP methods (like GET, POST) are handled as separate methods in a class, which helps with code organization and reusability.

Advantages of CBVs

crudOperations
  • CreateView - create or add new entries in a table in the database. 
  • Retrieve Views - read, retrieve, search, or view existing entries as a list(ListView) or retrieve a particular entry in detail (DetailView
  • UpdateView - update or edit existing entries in a table in the database 
  • DeleteView - delete, deactivate, or remove existing entries in a table in the database 
  • FormView - render a form to template and handle data entered by user

Django Class Based Views CRUD Operations

Illustration ofHow to create and use CRUD views using an example, consider a project named "geeksforgeeks" having an app named "geeks".  

Refer to the following articles to check how to create a project and an app in Django. 

Let’s now see how to implement CRUD operations using CBVs in Django.

Step 1: Define the Model

The first step is to define the model in Django. For our example, let’s create a model named GeeksModel to store the title and description of a record.

Ingeeks/models.py:

Python
fromdjango.dbimportmodelsclassGeeksModel(models.Model):title=models.CharField(max_length=200)description=models.TextField()def__str__(self):returnself.title

Explanation:

  • title:A CharField for the title of the record.
  • description:A TextField for the description of the record.

Run the following commands to create and apply database migrations:

Python manage.py makemigrations
Python manage.py migrate

Step 2: Create a ModelForm

To make it easier to create and update GeeksModel instances, let’s create a ModelForm. This form automatically generates a form for the model’s fields.

Ingeeks/forms.py:

Python
fromdjangoimportformsfrom.modelsimportGeeksModelclassGeeksForm(forms.ModelForm):classMeta:model=GeeksModelfields=["title","description",]

Explanation:

  • GeeksForm: A form class that generates a form for GeeksModel with fields title and description

Step 3: Create Class-Based Views

CreateView (For Creating Entries)

The CreateView class-based view provides the functionality to create new database records. We will use it to add new GeeksModel entries.

Ingeeks/views.py:

Python
fromdjango.views.generic.editimportCreateViewfrom.modelsimportGeeksModelclassGeeksCreate(CreateView):model=GeeksModelfields=['title','description']template_name='geeks/geeksmodel_form.html'success_url='/'

Explanation:

  • model: Specifies the model that the view will work with.
  • fields:Specifies the fields that will be displayed on the form.
  • template_name: Points to the HTML template where the form will be rendered.
  • success_url: Defines the URL to redirect to after successfully creating a new entry.

reate the corresponding templategeeks/geeksmodel_form.html:

HTML
<formmethod="POST">    {% csrf_token %}    {{ form.as_p }}<inputtype="submit"value="Submit"></form>

URL Mapping:In geeks/urls.py, map theGeeksCreate view:

Python
fromdjango.urlsimportpathfrom.viewsimportGeeksCreateurlpatterns=[path('create/',GeeksCreate.as_view(),name='geeks_create'),]

Let's check what is there on "http://localhost:8000/" 

django-create-view-function-based

To check complete implementation of Class based CreateView, visitCreateview – Class Based Views Django

ListView (For Retrieving Multiple Entries)

The ListView class-based view is used to retrieve and display a list of records.

Ingeeks/views.py:

Python
fromdjango.views.generic.listimportListViewfrom.modelsimportGeeksModelclassGeeksList(ListView):model=GeeksModeltemplate_name='geeks/geeksmodel_list.html'context_object_name='geeks_list'

Create the corresponding template geeks/geeksmodel_list.html:

HTML
<ul><!-- Iterate over object_list -->    {% for object in object_list %}<!-- Display Objects --><li>{{ object.title }}</li><li>{{ object.description }}</li><hr/><!-- If object_list is empty  -->    {% empty %}<li>No objects yet.</li>    {% endfor %}</ul>

URL Mapping:In geeks/urls.py, map theGeeksList view:

Python
fromdjango.urlsimportpathfrom.viewsimportGeeksListurlpatterns=[path('',GeeksList.as_view(),name='geeks_list'),]

Let's check what is there on "http://localhost:8000/"

django-listview-class-based-views

To check complete implementation of Class based ListView, visitListView – Class Based Views Django

DetailView (For Retrieving a Single Entry)

The DetailView is used to display detailed information about a single record.

Ingeeks/views.py:

Python
fromdjango.views.generic.detailimportDetailViewfrom.modelsimportGeeksModelclassGeeksDetailView(DetailView):# specify the model to usemodel=GeeksModel

Now create a url path to map the view. In geeks/urls.py, 

Python
fromdjango.urlsimportpath# importing views from views..pyfrom.viewsimportGeeksDetailViewurlpatterns=[# <pk> is identification for id field,# slug can also be usedpath('<pk>/',GeeksDetailView.as_view()),]

Create a template in templates/geeks/geeksmodel_detail.html, 

HTML
<h1>{{ object.title }}</h1><p>{{ object.description }}</p>

Let's check what is there on "http://localhost:8000/1/"

django-detailview-class-based

To check complete implementation of Class based DetailView, visitDetailView – Class Based Views Django 

UpdateView (For Updating Entries)

The UpdateView allows you to edit an existing record.

Ingeeks/views.py:

Python
fromdjango.views.generic.editimportUpdateViewfrom.modelsimportGeeksModelclassGeeksUpdateView(UpdateView):model=GeeksModelfields=["title","description"]success_url="/"

Now create a url path to map the view. In geeks/urls.py, 

Python
fromdjango.urlsimportpathfrom.viewsimportGeeksUpdateViewurlpatterns=[path('<pk>/update',GeeksUpdateView.as_view()),]

Create a template in templates/geeks/geeksmodel_form.html, 

HTML
<formmethod="post">    {% csrf_token %}    {{ form.as_p }}<inputtype="submit"value="Save"></form>

Let's check what is there on "http://localhost:8000/1/update/" 

django-updateview-class-based-view

To check complete implementation of Class based UpdateView, visitUpdateView – Class Based Views Django

DeleteView (For Deleting Entries)

The DeleteView allows you to delete a record from the database.

Ingeeks/views.py:

Python
fromdjango.views.generic.editimportDeleteViewfrom.modelsimportGeeksModelclassGeeksDeleteView(DeleteView):model=GeeksModelsuccess_url="/"

Now create a url path to map the view. In geeks/urls.py, 

Python
fromdjango.urlsimportpathfrom.viewsimportGeeksDeleteViewurlpatterns=[path('<pk>/delete/',GeeksDeleteView.as_view()),]

Create a template in templates/geeks/geeksmodel_confirm_delete.html, 

HTML
<formmethod="post">{% csrf_token %}<p>Are you sure you want to delete "{{ object }}"?</p><inputtype="submit"value="Confirm"></form>

Let's check what is there on "http://localhost:8000/1/delete"

django-deleteview-class-based-views

To check complete implementation of Class based DeleteView, visitDeleteView – Class Based Views Django

FormView (For Handling Forms)

The FormView is used to display and process forms. It provides a way to handle form submissions using CBVs.

Ingeeks/views.py:

Python
fromdjango.views.generic.editimportFormViewfrom.formsimportGeeksFormclassGeeksFormView(FormView):form_class=GeeksFormtemplate_name="geeks / geeksmodel_form.html"success_url="/thanks/"

Create a template for this view in geeks/geeksmodel_form.html, 

HTML
<formmethod="post">    {% csrf_token %}    {{ form.as_p }}<inputtype="submit"value="Save"></form>

Map a url to this view in geeks/urls.py, 

Python
fromdjango.urlsimportpathfrom.viewsimportGeeksFormViewurlpatterns=[path('',GeeksFormView.as_view()),]

Now visit "http://127.0.0.1:8000/"

django-create-view-function-based

To check complete implementation of Class based FormView, visitFormView – Class Based Views Django


Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp