Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
After you have a project and an app, let’s create a model of which we will be
creating instances through our view. In mcatutorials/models.py,
# import the standard Django Model
# from built-in library
from django.db import models
After creating this model, we need to run two commands in order to create
Database for the same.
Python manage.py makemigrations
Python manage.py migrate
Now we will create a Django ModelForm for this model. Refer this article for
more on modelform – Django ModelForm – Create form from Models. create a
file forms.py in mcatutorials folder,
from django import forms
from .models import McatutorialsModel
# creating a form
class McatutorialsForm(forms.ModelForm):
Create View
Create View refers to a view (logic) to create an instance of a table in the
database. It is just like taking an input from a user and storing it in a specified
table.
In mcatutorials/views.py,
from django.shortcuts import render
def create_view(request):
# dictionary for initial data with
# field names as keys
context ={}
context['form']= form
return render(request, "create_view.html", context)
def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
{% endfor %}
< /div>
To check complete implementation of Function based List View, visit List View
– Function based Views Django
Detail View
Detail View refers to a view (logic) to display a particular instnace of a table
from the database with all the necessary details. It is used to display multiple
types of data on a single page or view, for example, profile of a user.
In mcatutorials/views.py,
from django.urls import path
urlpatterns = [
path('< id>', detail_view ),
]
< /div>
In mcatutorials/templates/detail_view.html,
< div class="main">
< !-- Display attributes of instance -->
{{ data.title }} < br/>
{{ data.description }}
< /div>