0% found this document useful (0 votes)
33 views

Working With Django Models - Views - TEM

The document discusses Django models and databases. It explains how to configure a database in Django, define model classes, run migrations to create database tables, access and display data from models in templates, and use the Django admin interface.

Uploaded by

selemondoc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Working With Django Models - Views - TEM

The document discusses Django models and databases. It explains how to configure a database in Django, define model classes, run migrations to create database tables, access and display data from models in templates, and use the Django admin interface.

Uploaded by

selemondoc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

=============================

Working with Models & Databases


=============================
-->As part of web application development, we are required to interact with a database to store our
data and retrieve our stored data.
-->Django provides in-built support for database operations. Django provides one in-built database
sqlite3.
-->For small to medium applications, this database is more than enough. Django can provide support
for other databases also, like Oracle, Mysql, MongoDB etc…

Database Configuration:
-----------------------
-->Django, by default, provides sqlite3 database. If we want to use this database, we are not required
to do any configuration.
-->The default sqlite3 configurations in settings.py file are declared as:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

Database connection with Mysql:


--------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangodb',
'USER':'root',
'PASSWORD':'root',
'HOST':'localhost',
'PORT':3306,
}
}

SQL> select * from global_name;

Database connection with Oracle:


---------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'ORCL',
'USER':'scott',
'PASSWORD':'tiger',
'HOST':'localhost',
'PORT':1521,
}
}

-->If we dont want to use sqlite3 database then we have to configure our own database with the
following parameters.
1).ENGINE:Name of the database engine
2).NAME:Database name.
3).USER:Database login user name.
4).PASSWORD:Database login password.
5).HOST:The machine on which database server is running.
6).PORT:The port number on which database server is running.

Note: Most of the time HOST and PORT are optional.

How to check Django Database Connection:


-----------------------------------------
-->We can check whether django database configurations are properly configured or not by using the
command from shell.

D:\Django_VN1\Babunewsproject>py manage.py shell


>>> from django.db import connection
>>> c = connection.cursor()
-->If we are not getting any error means our database configurations are proper.

Model Class:
------------
-->A model is a python class which contains database information.
-->It contains fields and behaviours of the data what we are storing.
-->Each model maps to one database table.
-->Every model is a python class which is the child class of (django.db.models.Model)
-->Each attribute of the model represents database field(column name in table).
-->We have to write model classes inside 'models.py' file.

###############
###############

App:
----
D:\Django_VN1>django-admin startproject modelproject
D:\Django_VN1>cd modelproject
D:\Django_VN1\modelproject>py manage.py startapp testapp

-->Add app in settings.py

models.py
---------
class Employee(models.Model):
eno = models.IntegerField()
ename = models.CharField(max_length=30)
esal = models.FloatField()
eaddr = models.CharField(max_length=30)

Note:
This model classw ill be converted into database table. Django is responsible for this
conversion.

table_name:appname_classname
:testapp_Employee

Fields:eno,ename,esal and eaddr and one extra filed:id


Behaviours:eno integers, ename is char........
Model class = database table name + field name + field behaviours

Converting Model class into Database-specific SQL code:


-------------------------------------------------------
-->Once we write the model class, we have to migrate the corresponding SQL code; for this, we have
to use makemigrations.

D:\Django_VN1\modelproject>py manage.py makemigrations

How to see the corresponding SQL code of migrations:


----------------------------------------------------
D:\Django_VN1\modelproject>py manage.py sqlmigrate testapp 0001
BEGIN;
--
-- Create model Employee
--
CREATE TABLE "testapp_employee" ("id" integer NOT NULL PRIMARY KEY
AUTOINCREMENT, "eno" integer NOT NULL, "ename" varchar(30) NOT NULL, "esal" real NOT
NULL, "eaddr" varchar(30) NOT NULL);
COMMIT;

How to execute generated SQL code:


-----------------------------------
After generating sql code, we have to execute that sql code to create table in database. For this we
have to use 'migrate' command.
D:\Django_VN1\modelproject>py manage.py migrate

What is the advantage of creating tables with 'migrate' command:


----------------------------------------------------------------
If we use migrate command, then all django required tables will be created in addition to our
application specific tables. If we create table manually with sql code, then only our application
specific table will be created and django may not work properly. Hence it is highly recommended to
create tables with 'migrate' command.

How to check created table in Django admin interface:


-----------------------------------------------------
We have to register model class in admin.py

admin.py
--------------
from testapp.models import Employee
# Register your models here.
admin.site.register(Employee)

Creation of Super User to login to admin interface:


----------------------------------------------------
-->We can create super user by using the command

D:\Django_VN1\modelproject>py manage.py createsuperuser


Username (leave blank to use 'Babu'):
Email address: [email protected]
Password:
Password (again):
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

-->Start server send request and login to admin interface by using


http://127.0.0.1:8000/admin/

Read data from the database and display it for the end user.
----------------------------------------------------------
1).Start project
2).Start app
3).Add app in settings.py
4).Add database configurations in settings.py
5).Test database connections.
6).Create Model class.
7).Makemigrations and migrate.
8).Register model and adminmodel inside admin.py.
9).Createsuperuser.
10).Login to admin interface and check table created or not.
11).Template file and static file and corresponding configurations in settings.py
12).view function to communicate with database and to get data send this data to template file which
is responsible to display end user.

###############
###############

D:\Django_VN1>django-admin startproject modelproject2


D:\Django_VN1>cd modelproject2
D:\Django_VN1\modelproject2>py manage.py startapp testapp

-->Add app in settings.py

models.py
----------
class Employee(models.Model):
eno = models.IntegerField()
ename = models.CharField(max_length=30)
esal = models.FloatField()
eaddr = models.CharField(max_length=40)

-->makemigrations and migrate.

-->Register model class and ModelAdmin class in admin.py

admin.py
---------
from testapp.models import Employee
class EmployeeAdmin(admin.ModelAdmin):
list_display = ['eno','ename','esal','eaddr']
admin.site.register(Employee,EmployeeAdmin)

-->Createsuperuser:
D:\Django_VN1\modelproject2>py manage.py createsuperuser

-->Login to admin and add some data to table.


views.py
---------
from testapp.models import Employee
def empdata_view(request):
emp_list = Employee.objects.all()
print(type(emp_list))
my_dict = {'emp_list':emp_list}
return render(request,'testapp/emp.html',my_dict)

emp.html
---------
<body>
<h1>Employee List</h1>
{% if emp_list %}
<table border="3">
<thead>
<th>ENO</th>
<th>ENAME</th>
<th>ESAL</th>
<th>EADDR</th>
</thead>
{% for emp in emp_list %}
<tr>
<td>{{emp.eno}}</td>
<td>{{emp.ename}}</td>
<td>{{emp.esal}}</td>
<td>{{emp.eaddr}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No Records Found</p>
{% endif %}
</body>

emp1.css
---------
body{
background: yellow;
color: red;
}
h1{
text-align: center;
}
table{
margin: auto;
}

urls.py
-------
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/', views.empdata_view),
]

MVT:
---
V-->View Function/Class--->Business Logic--->Python code/Controller
T-->Template--->Presentation logic(HTML code)
M-->Model-->Related to database.

1).End user sending the request:


http://127.0.0.1:8000/emp/

2).View function will get the request:


def empdata_view(request):
emp_list = Employee.objects.all()
print(type(emp_list))
my_dict = {'emp_list':emp_list}
return render(request,'testapp/emp.html',my_dict)

3).View asking model to connect with database and provide required data.
emp_list = Employee.objects.all()

4).Model will communicate with database and provide required data to the view function.
emp_list = Employee.objects.all()

5).View will send that data to template file.


my_dict = {'emp_list':emp_list}
return render(request,'testapp/emp.html',my_dict)

6).Template file will prepare HttpResponse with required data and provide to view function.

7).View returns HTTP response to the end user.

Questions related models and templates?


---------------------------------------
1.How to configure database inside settings.py?
2.How to check the connections?
3.How to define model class inside models.py?
4.How to perform makemigrations?
5.How to perform migrate?
6.What is the diff between migrations and migrate?
7.What is the advantage of creating table by using migrate command instead of creating manually in
tha database?
8.How to add model to admin interface inside admin.py?
9.To display total data, how to write model admin class inside admin.py?
10.How to create superuser?
11.How to login to admin interface & add data to our table?
12.How to see generated sql code as result of makemigrations?

###############
###############

How to generate fake data:


--------------------------
-->By using faker module and our own customized code by using random module.
Way to generate fake data:
----------------------------------
django-seed is a django based customized application to generate fake data for every model
automatically.

Internally this application using faker module only.

steps to use django-seed:


-------------------------
1).pip install django-seed.
2).Add in settings.py

Generate fake data by using django-seed:


----------------------------------------
D:\Django_VN1\django-admin startproject modelproject4
D:\Django_VN1\modelproject4>py manage.py startapp testapp

-->Add 'testapp' and 'django_seed' in settings.py


-->Add database config in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'seeddb7am',
'USER':'root',
'PASSWORD':'root',
'HOST':'localhost',
'PORT':3306,
}
}

models.py
----------
class Student(models.Model):
rollno = models.IntegerField()
name = models.CharField(max_length=30)
dob = models.DateField()
marks = models.IntegerField()
email = models.EmailField()
phonenumber = models.CharField(max_length=30)
address = models.TextField()

-->Makemigrations and migrate.

admin.py
--------
from testapp.models import Student
class StudentAdmin(admin.ModelAdmin):
list_display = ['rollno','name','dob','marks','email','phonenumber','address']
admin.site.register(Student,StudentAdmin)

To insert data to the table:


py manage.py seed testapp --number=50
Project Name: Ethiopia Jobs
=======================

Addis Jobs Hawasa Job Adama Jobs

D:\Django_VN1>django-admin startproject ethiojobs


D:\Django_VN1>cd ethiojobs
D:\Django_VN1\ ethiojobs >py manage.py startapp testapp

-->Add app in settings.py

models.py
---------
class AddisJobs(models.Model):
date = models.DateField()
company = models.CharField(max_length=30)
title = models.CharField(max_length=30)
eligibility = models.CharField(max_length=30)
address = models.CharField(max_length=30)
email = models.EmailField()
phonenumber = models.BigIntegerField()
class HawasaJobs(models.Model):
date = models.DateField()
company = models.CharField(max_length=30)
title = models.CharField(max_length=30)
eligibility = models.CharField(max_length=30)
address = models.CharField(max_length=30)
email = models.EmailField()
phonenumber = models.BigIntegerField()
class AdamaJobs(models.Model):
date = models.DateField()
company = models.CharField(max_length=30)
title = models.CharField(max_length=30)
eligibility = models.CharField(max_length=30)
address = models.CharField(max_length=30)
email = models.EmailField()
phonenumber = models.BigIntegerField()

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'jobsdb7am',
'USER':'root',
'PASSWORD':'root',
'HOST':'localhost',
'PORT':3306,
}
}

Test database connection.


>>> from django.db import connection
>>> c = connection.cursor()

-->Makemigrations and migrate

admin.py
-------
from testapp.models import AddisJobs,HawasaJobs,AdamaJobs
class AddisJobsAdmin(admin.ModelAdmin):
list_display = ['date','company','title','eligibility','address','email','phonenumber']
admin.site.register(AddisJobs,AddisJobsAdmin)

class HawasaJobsAdmin(admin.ModelAdmin):
list_display = ['date','company','title','eligibility','address','email','phonenumber']
admin.site.register(HawasaJobs, HawasaJobsAdmin)

class AdamaJobsAdmin(admin.ModelAdmin):
list_display = ['date','company','title','eligibility','address','email','phonenumber']
admin.site.register(AdamaJobs, AdamaJobsAdmin)

views.py
--------
def homepage_view(request):
return render(request,'testapp/index.html')

index.html
----------
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Etjio Jobs</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-
xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/jobs1.css' %}">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Welcome To EthioJOBS</h1>
<p>Contenious Job Updates For Every Hour......</p>
<a class="btn btn-primary btn-lg" href="#" role='button'>Addis Ababa
Jobs</a>&nbsp&nbsp&nbsp&nbsp&nbsp
<a class="btn btn-primary btn-lg" href="#" role='button'>Hawasa
Jobs</a>&nbsp&nbsp&nbsp&nbsp&nbsp
<a class="btn btn-primary btn-lg" href="#" role='button'>Adama Jobs</a>
</div>

</div>
</body>
</html>
jobs1.css
---------
.container{
margin-top: 200px;
text-align: center;
}
.container .jumbotron{
background: red;
color: white;
}
.jumbotron a{
background: yellow;
color: red;
border: 2px solid green;
}

urls.py
----------
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.homepage_view),
]

###############
###############
views.py
---------
def addisjobs_view(request):
jobs_list = AddisJobs.objects.all()
my_dict = {'jobs_list':jobs_list}
return render(request,'testapp/addisjobs.html',my_dict)

addisjobs.html
------------
<body>
<h1>Addis Ababa Jobs Information</h1>
{% if jobs_list %}
<table border="2">
<thead>
<th>Date</th>
<th>Company</th>
<th>Title</th>
<th>Eligibility</th>
<th>Address</th>
<th>Email</th>
<th>PhoneNumber</th>
</thead>
{% for job in jobs_list %}
<tr>
<td>{{job.date}}</td>
<td>{{job.company}}</td>
<td>{{job.title}}</td>
<td>{{job.eligibility}}</td>
<td>{{job.address}}</td>
<td>{{job.email}}</td>
<td>{{job.phonenumber}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p id ='specialp'>No Jobs In AddisAbaba</p>
{% endif %}
</body>

populate(n)
print(f'{n} Records inserted successfully')

You might also like