Models - CRUD
Mrs.B.Santhi Priya,
Assistant Professor,
Department of Computer Science and Engineering
Kamaraj College of Engineering and Technology,
Virudhunagar.
1
CRUD
2
MVT – Model View Template
3
Model
• A model is the single, definitive source of information about your
data. It contains the essential fields and behaviors of the data you’re
storing. Generally, each model maps to a single database table.
• Model: The model is going to act as the interface of your data. It is
responsible for maintaining data. It is the logical data structure behind
the entire application and is represented by a database
4
Model Field
• A model field is a data type that stores a specific type of data. Each
model field represents specific data, such as numbers, dates, texts, or
even relationships with other models.
1. CharField - This field stores short-medium length characters or text
strings, which makes it suitable to store an attribute like a name.
CharField has a max_length parameter you must specify every time
you use the field.
Example:
name = models.CharField(max_length=20)
5
Model Field
2. DateField - This field stores dates in your model and has two
optional parameters (auto_now and auto_now_add). The auto_now
parameter sets the date every time you change or update data, while
the auto_now_add sets the field's date only when you create the data.
Example:
date_created = models.DateField(auto_now_add=True)
date_updated = models.DateField(auto_now=True)
6
Model Field
3. DateTimeField - This field stores the date and time information in a
model.
4. DecimalField - This field stores decimal numbers in a database.
Example
• price = models.DecimalField(max_digits=6, decimal_places=2)
5. BooleanField - This field stores boolean values.
6. EmailField - The EmailField is a specialized form of CharField that stores
email addresses.
7. TextField - TextField stores large amounts of text data. This field is
useful when storing text data that is too long for a CharField.
7
Model Field
8. IntegerField -This field stores integer values in the form of whole
numbers. These values range from -2147483648 to 0 for negative
integers and 0 to 2147483647 for positive integers.
9. ForeignKeyField - The ForeignKey field type creates a many-to-one
relationship between two models. This field is helpful when one model
(the child model) needs to reference another (the parent model). It has
two required parameters, the class to which the model is related and
the on_delete option.
8
Creating a New Project
• Activate the Virtual Environment
• C:\Users\ADMIN\Documents\Django Projects>cd django_env
• C:\Users\ADMIN\Documents\Django Projects\django_env>Scripts\activate
• (django_env) C:\Users\ADMIN\Documents\Django Projects\django_env>cd..
9
Creating a New Project
• (django_env) C:\Users\ADMIN\Documents\Django Projects>django-
admin startproject DemoCRUD
10
Creating a New APP
• Go to the Project Folder then create a new app
• (django_env) C:\Users\ADMIN\Documents\Django Projects>cd DemoCRUD
• (django_env) C:\Users\ADMIN\Documents\Django Projects\
DemoCRUD>python manage.py startapp operations
11
Integrate the App in setting.py
12
Creating a Model
• models.py
13
Django Database Migrations
• Migration is a way of applying changes that we have made to a model,
into the database schema.
• makemigrations : It is used to create a migration file that contains
code for the tabled schema of a model.
• (django_env)C:\Users\ADMIN\Documents\Django Projects\DemoCRUD>
python manage.py makemigrations
• Migrations for 'operations':
• operations\migrations\0001_initial.py
• - Create model Employee
14
Django Database Migrations
• migrate : It creates table according to the schema defined in the
migration file.
• (django_env) C:\Users\ADMIN\Documents\Django Projects\
DemoCRUD> python manage.py migrate
15
Creating a superuser
• (django_env) C:\Users\ADMIN\Documents\Django Projects\
DemoCRUD> python manage.py createsuperuser
• Username – admin
• Password – admin
16
To register the model in admin
• admin.py
17
To Run the server
• (django_env) C:\Users\ADMIN\Documents\Django Projects\
DemoCRUD>python manage.py runserver
18
Output
• Go to the browser and Type ->http://127.0.0.1:8000/
19
Output
• Go to the browser and Type ->http://127.0.0.1:8000/admin
20
Output
21
Output
22
Output
23
Templates
• A template is a text file. It can generate any text-based format (HTML,
XML, CSV, etc.).
• A template contains variables, which get replaced with values when
the template is evaluated, and tags, which control the logic of the
template.
24
Templates• Inside the operations, creating a folder is called
“templates”
• Inside the templates – created the 4 html file
(Index.html,create.html,delete.html,update.html)
25
Index.html
• <!DOCTYPE html>
• <html lang="en">
• <head>
• <meta charset="UTF-8">
• <meta name="viewport" content="width=device-width, initial-scale=1.0">
• <title>Document</title>
• </head>
• <body>
• homepage
• </body>
• </html>
26
Views
• A view function, or view for short, is a Python function that takes a
web request and returns a web response. This response can be the
HTML contents of a web page, or a redirect, or a 404 error, or an XML
document, or an image . . . or anything, really.
27
Views.py
28
Urls.py (creating a file inside the
app)
29
Include the Url in our Project
Include the App Url to the Project
30
Now You can check the output
• Go to the browser and Type - http://127.0.0.1:8000/
31
Output
• Go to the browser and Type - http://127.0.0.1:8000/create
• Go to the browser and Type - http://127.0.0.1:8000/update
32
Index.html
• Update the following code – Include the supporting file for bootstrap
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">KCET</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-
controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Create <span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
** - Include the Bootstrap CDN Links 33
Output
• Go to the browser and Type - http://127.0.0.1:8000/
34
Create Demo
35
Forms - Django
• Django provides a Form class which is used to create HTML forms. It
describes a form and how it works and appears.
• It is similar to the ModelForm class that creates a form by using the
Model
36
Create a file in Operations App
Folder – forms.py
37
Update the code in views.py
•When a request is made to the create view, an instance of
EmployeeForm is created.
•A context dictionary is prepared with this form instance.
•The create.html template is rendered, with the context dictionary passed
to it. This means that the form will be available in the template,
38 allowing
it to be displayed to the user.
Update the code Create.html
Import Bootstrap CDN Links
Import Bootstrap CDN Links
•CSRF Protection: The {% csrf_token %} tag ensures that a CSRF token is included for security.
•This is a Django template tag that inserts a CSRF (Cross-Site Request Forgery) token into the form.
•Form Fields: {{ form.as_p }} renders the form fields as HTML paragraphs. 39
Output
• Run the server - Go to the browser and Type http://
127.0.0.1:8000/create
40
Change the Alignment in Form
• Crispy form - Django Crispy Forms is a third-party Django application
that simplifies and enhances the way forms are rendered. It allows
developers to create beautiful, flexible, and DRY (Don't Repeat
Yourself) forms with minimal effort.
• To install the Crispy Form - pip install django-crispy-forms
• For Better Alignment install crispy-bootstrap4 - pip install crispy-
bootstrap4
41
Change the Alignment in Form
• Update the Settings.py file -
42
Change the Alignment in Form
• Update the create.html file - •Loading Custom Tags: In Django, template tags are special constructs that
provide additional functionality in templates. The {% load %} tag is used to load a
set of custom template tags and filters defined in a specific module.
•Crispy Forms Tags: The crispy_forms_tags is the specific module provided by
Django Crispy Forms that contains tags and filters for rendering forms in a more
flexible and visually appealing manner.
Create container class
Crsipy Form
43
Now See the Output
44
Update the file views.py
45
Output
• Run the server and go to the browser type - http://
127.0.0.1:8000/create
46
To check the output
• Go to the browser type - http://127.0.0.1:8000/admin
47
Read Demo
48
Update the Views.py file
Import models
•Database Query: Employee.objects.all() retrieves all records from the
Employee model.
•Context Dictionary: The result of the query is stored in a context dictionary
with the key 'data'.
•Rendering: The render function takes the request object, the name of the
template, and the context dictionary, and returns an HttpResponse object
with the rendered template.
49
index.html – To read the data from
Database
{% for emp in data %}: This is a Django template tag that starts a for
loop. It iterates over the data context variable, which is expected to be
a list (or QuerySet) of Employee objects. For each iteration, the
current Employee object is assigned to the variable emp.
- **`{{ emp.name }}`**: This outputs the `name` attribute of the current
`Employee` object.
- **`{{ emp.email }}`**: This outputs the `email` attribute of the current
`Employee` object.
- **`{{ emp.address }}`**: This outputs the `address` attribute of the
current `Employee` object.
- **`{{ emp.jobrole }}`**: This outputs the `jobrole` attribute of the
current `Employee` object.
**Ending the Loop**:
{% endfor %}
50
Now let’s see the output
We read the data but alignment
was not good,
Create the table and display the
content
51
Update the index.html file
<div class="container"> <tr>
<h1>Employee Details</h1> <td> {{emp.name}}</td>
<td>{{emp.email}}</td>
<table class="table table-bordered">
<td>{{emp.address}}</td>
<tr>
<td>{{emp.jobrole}}</td>
<th>Name</th> <td>
<th>Email ID</th> <button class="btn btn-primary"><a href="#">Update</a></button>
<th>Address</th> <button class="btn btn-danger"><a href="#">Delete</a></button>
<th>Job Role</th> </td>
</tr>
<th>Operations</th>
{% endfor %}
</tr>
</table>
{% for emp in data %} </div>
52
Output
53
Update Demo
54
Check the Database
Every record has the unique ID, based on the ID only
we have to update the records 55
Update.html
• Copy the create.html and paste it here
56
Views.py
57
Urls.py
58
Index.html
See the ID
Now I am clicking the first data
It will pass the first ID
59
Data to be Updated
60
Delete Demo
61
Delete the record from the Database
Views.py Urls.py
Index.html
62
Output
Before Delete After Delete
63
64