Python
Python
PROGRAMMING CONCEPTS
One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
attributes
behavior
Parrot is an object,
The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).
Class
We can think of class as an sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here,
parrot is an object.
class Parrot:
pass
Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.
Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.
Blu is a bird
In the above program, we create a class with name Parrot. Then, we define attributes. The
attributes are a characteristic of an object.
Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our
new objects.
Then, we access the class attribute using __class __.species. Class attributes are same for all
instances of a class. Similarly, we access the instance attributes using blu.name and blu.age.
However, instance attributes are different for every instance of a class.
To learn more about classes and objects, go to Python Classes and Objects
Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
4
In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.
Inheritance
Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Run
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this
from swim()method. Again, the child class modified the behavior of parent class. We can see
this from whoisThis() method. Furthermore, we extend the functions of parent class, by
creating a new run() method.
Additionally, we use super() function before __init__() method. This is because we want to
pull the content of __init__() method from the parent class into the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevent data
from direct modification which is called encapsulation. In Python, we denote private attribute
using underscore as prefix i.e single “ _ “ or double “ __“.
In the above program, we defined a class Computer. We use __init__() method to store the
maximum selling price of computer. We tried to modify the price. However, we can’t change
it because Python treats the __maxprice as private attributes. To change the value, we used a
setter function i.e setMaxPrice() which takes price as parameter.
Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form (data types).
Suppose, we need to color a shape, there are multiple shape option (rectangle, square, circle).
However we could use same method to color any shape. This concept is called
Polymorphism.
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
7
In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
8
CHAPTER 3
PROGRAMMING CONCEPTS
Introduction to OOPs in Python
One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
attributes
behavior
Parrot is an object,
The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).
Class
We can think of class as an sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here,
parrot is an object.
class Parrot:
pass
Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.
Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.
Blu is a bird
In the above program, we create a class with name Parrot. Then, we define attributes. The
attributes are a characteristic of an object.
Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our
new objects.
Then, we access the class attribute using __class __.species. Class attributes are same for all
instances of a class. Similarly, we access the instance attributes using blu.name and blu.age.
However, instance attributes are different for every instance of a class.
To learn more about classes and objects, go to Python Classes and Objects
Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
11
In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.
Inheritance
Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Run
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this
from swim()method. Again, the child class modified the behavior of parent class. We can see
this from whoisThis() method. Furthermore, we extend the functions of parent class, by
creating a new run() method.
Additionally, we use super() function before __init__() method. This is because we want to
pull the content of __init__() method from the parent class into the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevent data
from direct modification which is called encapsulation. In Python, we denote private attribute
using underscore as prefix i.e single “ _ “ or double “ __“.
In the above program, we defined a class Computer. We use __init__() method to store the
maximum selling price of computer. We tried to modify the price. However, we can’t change
it because Python treats the __maxprice as private attributes. To change the value, we used a
setter function i.e setMaxPrice() which takes price as parameter.
Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form (data types).
Suppose, we need to color a shape, there are multiple shape option (rectangle, square, circle).
However we could use same method to color any shape. This concept is called
Polymorphism.
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
14
In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
15
PYTHON MYSQL
Select
import PyMySQL
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
16
results = cursor.fetchall()
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
except:
import pymysql.cursors
try:
# SQL
sql = "SELECT Dept_No, Dept_Name FROM Department "
# Execute query.
17
cursor.execute(sql)
print()
finally:
# Close connection.
connection.close()
insert
import PyMySQL
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
connection = myconnutils.getConnection()
try :
cursor = connection.cursor()
# 1 row.
oneRow = cursor.fetchone()
grade = 1
grade = oneRow["Max_Grade"] + 1
cursor = connection.cursor()
connection.commit()
finally:
connection.close()
update
import PyMySQL
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
import myconnutils
import pymysql.cursors
import datetime
connection = myconnutils.getConnection()
try :
cursor = connection.cursor()
sql = "Update Employee set Salary = %s, Hire_Date = %s where Emp_Id = %s "
# Hire_Date
newHireDate = datetime.date(2002, 10, 11)
connection.commit()
finally:
# Close connection.
21
Delete
import PyMySQL
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
22
connection = myconnutils.getConnection()
try :
cursor = connection.cursor()
connection.commit()
finally:
# Close connection.
connection.close()
23
Python mail
https://myaccount.google.com/lesssecureapps
import smtplib
li = ["[email protected]"]
for i in range(len(li)):
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("[email protected]", "******")
s.quit()
Example1: google_search.py
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")
# to search
query = "n"
Use the API of the website (if it exists). For example, Facebook has the Facebook Graph
API which allows retrieval of data posted on Facebook.
Access the HTML of the webpage and extract useful information/data from it. This
technique is called web scraping or web harvesting or web data extraction.
pip install requests
pip install html5lib
pip install bs4
Step 2: Accessing the HTML content from webpag
import requests
from bs4 import BeautifulSoup
URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)
import os
def get_all_file_paths(directory):
file_paths = []
file_paths.append(filepath)
return file_paths
def main():
27
directory = 'folder'
file_paths = get_all_file_paths(directory)
print(file_name)
zip.write(file)
if __name__ == "__main__":
main()
Django
Introduction
This framework uses a famous tag line:The web framework for perfectionists
with deadlines.
History
Django was design and developed by Lawrence journal world in 2003 and publicly
released under BSD license in July 2005. Currently, DSF (Django Software
Foundation) maintains it?s development and release cycle.
Django initially released on 21, July 2005 and current stable version is 2.0.3 which
was released on 6 March, 2018.
Popularity
Django is widely accepted and used by various well-known sites such as:
Instagram
Mozilla
Disqus
Pinterest
Bitbucket
The Washington Times
Features of Django
Rapid Development
Secure
Scalable
Fully loaded
Versatile
Open Source
Vast and Supported Community
DJANGO- INSTALLATION
31
Installation
The first thing we need to do is install some programs on our machine so to be able
to start playing with Django. The basic setup consists of installing Python,
Virtualenv, and Django.
Pick the right version accordingly to your Windows distribution. If you are not sure
which one is the right for you, the chances are you want to download the Windows
x86-64 executable installer version.
Go to your Downloads directory, right click on the installer and click on Run as
administrator.
32
Make sure you check the option Add Python 3.6 to PATH and click on the Install
Now option.
After the installation completes, you should see the following screen:
33
Now search for the Command Prompt program and open it:
python --version
Python 3.6.2
34
Installing Virtualenv
This folder is the higher level directory that will store all the files and things related
to our Django project, including its virtual environment.
So let’s start by creating our very first virtual environment and installing Django.
virtualenv venv
35
Our virtual environment is created. Now before we start using it, we need to
activate:
venv\Scripts\activate
You will know it worked if you see (venv) in front of the command line, like this:
venv\Scripts\deactivate.bat
It’s very straightforward. Now that we have the venv activated, run the following
command to install Django:
After we run the command above, it will generate the base folder structure for a
Django project.
__init__.py: this empty file tells Python that this folder is a Python package.
settings.py: this file contains all the project’s configuration. We will refer to this
file all the time!
urls.py: this file is responsible for mapping the routes and paths in our project. For
example, if you want to show something in the URL /about/, you have to map it
here first.
wsgi.py: this file is a simple gateway interface used for deployment. You don’t have
to bother about it. Just let it be for now.
For now, you can ignore the migration errors; we will get to that later.
Now open the following URL in a Web browser: http://127.0.0.1:8000 and you
should see the following page:
38
Django Apps
app: is a Web application that does something. An app usually is composed of a set
of models (database tables), views, templates, tests.
Alright! So, to illustrate let’s create a simple Web Forum or Discussion Board. To
create our first app, go to the directory where the manage.py file is and executes
the following command:
myproject/
|-- myproject/
| |-- boards/ <-- our new django app!
| | |-- migrations/
| | | +-- __init__.py
| | |-- __init__.py
| | |-- admin.py
| | |-- apps.py
| | |-- models.py
| | |-- tests.py
| | +-- views.py
| |-- myproject/
| | |-- __init__.py
| | |-- settings.py
39
| | |-- urls.py
| | |-- wsgi.py
| +-- manage.py
+-- venv/
migrations/: here Django store some files to keep track of the changes you create
in the models.py file, so to keep the database and the models.py synchronized.
admin.py: this is a configuration file for a built-in Django app called Django
Admin.
models.py: here is where we define the entities of our Web application. The models
are translated automatically by Django into database tables.
tests.py: this file is used to write unit tests for the app.
views.py: this is the file where we handle the request/response cycle of our Web
application.
Now that we created our first app, let’s configure our project to use it.
To do that, open the settings.py and try to find the INSTALLED_APPS variable:
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
As you can see, Django already come with 6 built-in apps installed. They offer
common functionalities that most Web applications need, like authentication,
sessions, static files management (images, javascripts, css, etc.) and so on.
We will explore those apps as we progress in this tutorial series. But for now, let
them be and just add our boards app to the list of INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
40
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'boards',
]
Using the analogy of the square and circles from the previous comic, the yellow
circle would be our boards app, and the django.contrib.admin,
django.contrib.auth, etc, would be the red circles.
Hello, World!Let’s write our first view. We will explore it in great detail in the
next tutorial. But for now, let’s just experiment how it looks like to create a new
page with Django.
Open the views.py file inside the boards app, and add the following code:
views.py
def home(request):
return HttpResponse('Hello, World!')
Views are Python functions that receive an HttpRequest object and returns an
HttpResponse object. Receive a request as a parameter and returns a response as a
result. That’s the flow you have to keep in mind!
So, here we defined a simple view called home which simply returns a message
saying Hello, World!.
Now we have to tell Django when to serve this view. It’s done inside the urls.py
file:
urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
41
If you compare the snippet above with your urls.py file, you will notice I added the
following new line: url(r'^$', views.home, name='home') and imported the views
module from our app boards using from boards import views.
As I mentioned before, we will explore those concepts in great detail later on.
But for now, Django works with regex to match the requested URL. For our home
view, I’m using the ^$ regex, which will match an empty path, which is the
homepage (this url: http://127.0.0.1:8000). If I wanted to match the URL
http://127.0.0.1:8000/homepage/, my url would be: url(r'^homepage/$',
views.home, name='home').
Django App
Creating an App
views.py
def hello(request):
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', views.hello),
localhost:8000/hello
43
Django MVT
The Template is a presentation layer that handles all the User Interface part. The
View is used to execute the business logic and interact with model to carry data and
renders template.
Django Session
In Django, by default session stores in the database and also allows file-based and
cache based sessions. It is implemented via a piece of middleware and can be
enabled by using the following code.
Put django.contrib.sessions.middleware.SessionMiddleware in
MIDDLEWARE and django.contrib.sessions in INSTALLED_APPS of
settings.py file.
To set and get the session in views, we can use request.session and can set multiple
times too.
Method Description
Let's see an example in which we will set and get session values. Two functions are
defined in the views.py file.
The first function is used to set and the second is used to get session values.
//views.py
def setsession(request):
request.session['sname'] = 'irfan'
request.session['semail'] = '[email protected]'
return HttpResponse("session is set")
def getsession(request):
studentname = request.session['sname']
studentemail = request.session['semail']
return HttpResponse(studentname+" "+studentemail);
// urls.py
Run Server
Sending email using Django is pretty easy and require less configuration. In this
tutorial, we will send email to provided email.
For this purpose, we will use Google's SMTP and a Gmail account to set sender.
Before sending email, we need to make some changes in Gmail account because for
security reasons Google does not allow direct access (login) by any application. So,
login to the Gmail account and follow the urls. It will redirect to the Gmail account
settings where we need to allow less secure apps but toggle the button. See the
below screenshot.
https://myaccount.google.com/lesssecureapps
After that follow this url that is a additional security check to verify the make
security constraint.
48
https://accounts.google.com/DisplayUnlockCaptcha
Django Configuration
Provide the smtp and Gmail account details into the settings.py file. For example
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '*********'
Now, write a view function that uses built-in mail function to send mail. See the
example
// views.py
def mail(request):
subject = "Greetings"
msg = "Congratulations for your success"
49
to = "[email protected]"
res = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to])
if(res == 1):
msg = "Mail Sent Successfuly"
else:
msg = "Mail could not sent"
return HttpResponse(msg)
// urls.py
path('mail',views.mail)
Here, the both email ids are mine, so I can verify the email by login to the account.
Personally i prefer Postgres for my applications, however like all things some poeple
prefer others such as MySQL, MSSQL or even MongoDB.
50
To get started we need to confirm what version of Python you are running this can
be achieved by opening a command prompt and entering the following:
python --version
Mine is currently Python 3.6.3, this tutorial should work the same if you are using a
different version of Python however, the same results cannot be guaranteed.
We need a Virtualenv
As with any project we should always use a virtual environment, this allows us to
isolate the packages we have from our global Python install.
Lets get started by making sure we have one setup. But first we need to install
virtualenv if we dont already.
Now we need a place to store them for my projects i do the following structure:
Folder Structure
\path\to\your\virtualenv\Scripts\activate
We can confirm it is active by seeing (virtualenvname) before the CMD prompt, like
so:
51
Django, Mysql
The missing step here would be to ensure you have MySQL server installed on your
local machine aswell if you intend to develop on a local database initially. For this
example i will be connecting to a remote MySQL database.
We can now install Django and any other packages we want, for this example we
will just get MySQL.
This will download and install the packages. We will now setup our test application
and store the files in the app folder.
We can now build our DATABASES settings in our settings.py as follows, i will
using VS Code to edit.
The settings.py file contains all the project settings along with database connection
details. By default, Django works with SQLite, database and allows configuring for
other databases as well.
Database connectivity requires all the connection details such as database name,
user credentials, hostname drive name etc.
We need to provide all connection details in the settings file. The settings.py file of
our project contains the following code for the database.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangoApp',
'USER':'root',
'PASSWORD':'mysql',
'HOST':'localhost',
'PORT':'3306'
}
}
Migration is a way of applying changes that we have made to a model, into the
database schema. Django creates a migration file inside the migration folder for
each model to create the table schema, and each table is mapped to the model of
which migration is created.
53
Django provides the various commands that are used to perform migration related
tasks. After creating a model, we can use these commands.
makemigrations : It is used to create a migration file that contains code for the
tabled schema of a model.
migrate : It creates table according to the schema defined in the migration file.
After providing details, check the connection using the migrate command.
Migrating Model
Well, till here, we have learned to connect Django application to the MySQL
database. Next, we will see how to create a table using the model.
Each Django's model is mapped to a table in the database. So after creating a model,
we need to migrate it. Let's see an example.
Suppose, we have a model class Employee in the models.py file that contains the
following code.
// models.py
econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"
Django first creates a migration file that contains the details of table structure. To
create migration use the following command.
The created migration file is located into migrations folder and contains the
following code.
Before we start writing applications, we must know a little about what is Django.
Django is a web application framework that acts more of an MTV pattern instead of
MVC. Think it this way:
A simple Hello-world application is just a few lines of code in Django! But moving
from this simple thing a full fledged application can be a daunting task in itself. There
are other concepts that can help proceed further such as ORM, migrations etc that help
in building a bigger application. But for this we’ll be building a simple CRUD( Create,
Retrieve, Update and Delete ) application.
To get started with you need to have python and virtualenv installed on your machine.
Python is already installed on the linux systems. But you'll need to install virtualenv.
To install virtualenv follow the command:
56
Before we actually start writing code we need to get a hold of the application structure.
We'll first execute several commands that are essential in django project development.
virtualenv venv
We are setting a virtual environment of the name venv here. Now we need to activate
it.
source venv/bin/activate
cd venv
Now that it has been activated. We need to start our project. Feed in the following
command to start a project.
pip install django==1.11.8
mkdir app && cd app
django-admin startproject crudapp
view rawinstallation.md
The first line installs Django v1.11.8 and creates a directory named app in the parent
directory. the third line starts a project named crudapp in the app directory. The
directory tree should look like
app
└── crudapp
├── crudapp
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
We'll see the meaning of each file and what it does one by one. But first, to test if you
are going in the right directoion, run the following command.
57
Let's see what exactly the different files that we created mean.
__init__.py : Acts as an entry point for your python project.
settings.py : Describes the configuration of your Django installation and lets
Django know which settings are available.
urls.py : used to route and map URLs to their views.
wsgi.py : contains the configuration for the Web Server Gateway Interface. The
Web Server Gateway Interface (WSGI) is the Python platform standard for the
deployment of web servers and applications.
Writing the Application
Now this is where we start coding our app. For this operation we'll consider blog post
as our entity. We'll be applying CRUD operations to blog posts.
def __unicode__(self):
return self.title
def get_post_url(self):
return reverse('post_edit', kwargs={'pk': self.pk})
Now that we have our model ready, we'll need to migrate it to the database.
python manage.py makemigrations
python manage.py migrate
Now we create our Views where we define each of our CRUD definition.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class PostsForm(ModelForm):
class Meta:
model = blog_posts
fields = ['id', 'title', 'author']
"""
crudapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
from django.conf.urls import url
from django.contrib import admin
from blog_posts import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.post_list, name='post_list'),
url(r'^new$', views.post_create, name='post_new'),
url(r'^edit/(?P<pk>\d+)$', views.post_update, name='post_edit'),
url(r'^delete/(?P<pk>\d+)$', views.post_delete, name='post_delete'),
]
Now we create project specific mappings in /crudapp/crudapp/urls.py.
"""
Crudapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
from django.conf.urls import url, include
from django.contrib import admin
from crudapp.views import home
urlpatterns = [
url(r'^admin/', admin.site.urls),
60
Now almost everything is done and all we need to do is create our templates to test the
operations.
Go ahead and create a templates/blog_posts directory in crudapp/blog_posts/.
templates/blog_posts/post_list.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
beta.2/css/bootstrap.min.css">
<title>Django CRUD application!</title>
</head>
<body>
<div class="container">
<h1>Blog Post List!</h1>
<ul>
{% for post in object_list %}
<li><p>Post ID: <a href="{% url "blog_posts:post_edit" post.id %}">{{
post.id }}</a></p>
<p>Title: {{ post.title }}</p>
<a href="{% url "blog_posts:post_delete" post.id %}">Delete</a>
</li>
{% endfor %}
</ul>
Now we have all the necessary files and code that we require.
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ ├── wsgi.py
├── db.sqlite3
├── manage.py
└── requirements.txt
Execute python manage.py runserver and voila!! You have your Django app ready.