Working With Django Models - Views - TEM
Working With Django Models - Views - TEM
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',
}
}
-->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.
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
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
admin.py
--------------
from testapp.models import Employee
# Register your models here.
admin.site.register(Employee)
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.
###############
###############
models.py
----------
class Employee(models.Model):
eno = models.IntegerField()
ename = models.CharField(max_length=30)
esal = models.FloatField()
eaddr = models.CharField(max_length=40)
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
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.
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()
6).Template file will prepare HttpResponse with required data and provide to view function.
###############
###############
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()
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)
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,
}
}
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>     
<a class="btn btn-primary btn-lg" href="#" role='button'>Hawasa
Jobs</a>     
<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')