Vous êtes sur la page 1sur 20

Django – Handbook

Open learning… Knowledge sharing...

@Copyleft 2019, Sandeep Basva <sandeepbasva@swecha.net>

version: 1.0(Beta)
Django Material

What is Django..?

Django is the largest python framework used to build websites.


Django developed by Adrian Holovaty and Simon Willison at Lawrence Journal World news
paper in 2003.
The first public version is released in 2005.

Django Design Principles:

 Don’t Repeat Yourself (DRY) Principle


Fast Development
Less coding
 Explicit Is Better Than Implicit
Clean Design
 Loosely Coupled Architecture
Features of Django:

 Open source
 Object-Relational Mapping (ORM) Support
-Model to Database
 Administration GUI
 Multilingual Support
 Performance
-Using less memory
 Secure
-Prevents SQL injection, cross-site request forgery
 Huge Libraries
 Widely Scalable
-Mini projects to Big Projects
 Development Environment
-In-built http server
Django architecture:

Django is an MVT framework


Websites built with Django Framework:
 YouTube

 Instagram

 Mozilla Firefox

 Bitbucket

 SunNXT

 Event Brite

 Dropbox

 The washington post

 Vodafone Play

Install django:

install pip3
sudo apt-get install python3-pip
pip3 --version
pip install django==1.11.2
django-admin.py version

OR
Install django using virtual environment
install pip3
sudo apt-get install python3-pip
pip3 --version
#pip install --upgrade pip
pip3 install virtualenv
virtualenv -p python3 django11
django11/
source django11/bin/activate
cd Projects/
pip --version
pip install django==1.11.2
django-admin.py version

Project:

django-admin startproject camp


cd camp/
python manage.py runserver

Django project structure:

+camp(<BASE_DIR_project_name>)
|
+----manage.py
|
+---+-camp(<PROJECT_DIR_project_name>)
|
+-__init__.py
+-settings.py
+-urls.py
+-wsgi.py

manage.py .- Runs project specific tasks. Just as django-admin is used to execute system
wide Django tasks, manage.py is used to execute project specific tasks.
__init__.py .- Python file that allows Python packages to be imported from directories where
it’s present. Note __init__.py is not Django specific, it’s a generic file used in almost all
Python applications.
settings.py .- Contains the configuration settings for the Django project.
urls.py .- Contains URL patterns for the Django project.
wsgi.py .- Contains WSGI configuration properties for the Django project. WSGI is
the recommended approach to deploy Django applications on production (i.e., to
the public). You don’t need to set up WSGI to develop Django applications.

Create App:

python manage.py startapp timeapp


Register app in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'timeapp',
]

Structure:

+camp(<BASE_DIR_project_name>)
|
+----manage.py
|
+---+-camp(<PROJECT_DIR_project_name>)
|
+-__init__.py
+-settings.py
+-urls.py
+-wsgi.py
+---+timeapp(<APP_DIR_app_name>)
|
+-migrations(Migrations Directory)
+-__init__.py
+-__init__.py
+-admin.py
+-models.py
+-tests.py
+views.py

__init__.py − Just to make sure python handles this folder as a package.


admin.py − This file helps you make the app modifiable in the admin interface.

models.py − This is where all the application models are stored.

tests.py − This is where your unit tests are.

views.py − This is where your application views are.

1. Hello World:

In views.py:
"""This module contains business logic of our app,
It will communicate with database and templates"""
author = 'Sandeep Basva'
email = 'sandeepbasva@swecha.net'

from django.http import HttpResponse


# Create your views here.

def hello(request):
"""A view to display Hello World"""
return HttpResponse("Hello World")

In urls.py

from django.conf.urls import url


from django.contrib import admin
from timeapp.views import hello

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', hello)
]

Another one:

def hello(request):
"""A view to display Hello World"""
text = HttpResponse()
text.write("<htm><head>")
text.write("<title>Sample</title></head>")
text.write("<body><p>Hello friends,<p>")
text.write("<p>Welcome to Winter camp..</p></body>")
return text
2. Time app:

In views.py:
Import datetime
def time(request):
time = datetime.datetime.now()
return HttpResponse(time)

url(r'^time$', time),

Future time:
In views.py:

def time_diff(request, offset):


hours = int(offset)
time = datetime.datetime.now()
new_time = datetime.timedelta(hours=hours)+time
return HttpResponse(new_time)

In urls.py:
from django.conf.urls import url
from django.contrib import admin
from timeapp.views import hello, time, time_diff

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', hello),
url(r'^time$', time),
url(r'^time/plus/(\d{1,2})/$', timedelta)

Time using HTML:

In views.py:

def time_diff2(request, offset):


res = HttpResponse()
hours = int(offset)
time = datetime.datetime.now()
res.write("<p>The present time is %s"%time)
new_time = datetime.timedelta(hours=hours)+time
res.write("<p>The time after %s hours is %s"%(hours,new_time))
return res
Improving views using templates:

Create templates folder in inner project directory i.e.., camp/camp


Set path to templates folder in settings.py file.Type the path in DIRS of TEMPLATES

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["camp/templates", ],

In camp/templates/c_time.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Current Date and Time</title>
</head>
<body>
<h1>The current time is {{c_time}}.</h1>

</body>
</html>

In views.py:

from django.shortcuts import render


from django.http import HttpResponse
from django.template.loader import get_template
import datetime

def ttime(request):
time = datetime.datetime.now()
template = get_template("c_time.html")
res = template.render({'c_time': time})
return HttpResponse(res)

(OR)

def ttime(request):
time = datetime.datetime.now()
return render(request, "c_time.html",{'c_time': time})

In urls.py:

url(r'^time/template/$', ttime),

Future time using templates:


In camp/templates/f_time.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Current Date and Time</title>
</head>
<body>
<h1>The current time is {{c_time}}.</h1>
<h1>The time after {{hours}} hours is {{f_time}}.</h1>

<p>Thanks for visiting my page.</p>

</body>
</html>

In views.py:

def ttime_diff(request, offset):


hours = int(offset)
time = datetime.datetime.now()
new_time = datetime.timedelta(hours=hours)+time
return render(request, "f_time.html", {'c_time': time, 'hours': hours, 'f_time': new_time})

In urls.py:
url(r'^time/templates/(\d{1,2})/$', ttime_diff),

Template Inheritance:

To eliminate the duplicate HTML code that repeats in every template, we use template
inheritance concept.

base.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<h1> Getting time from template</h1>
{% block content %} {% endblock %}
<hr>
<p> Thanks for visiting my page</p>

</body>
</html>
c_time2.html:

{% extends "base.html" %}
{% block title %} The current time{% endblock %}
{% block content %}<p>It is now {{c_time}}</p> {% endblock %}

f_time2.html:

{% extends "base.html" %}
{% block title %} The future time{% endblock %}
{% block content %}<p>The current time is {{c_time}}.</p>
<p>The time after {{hours}} hours is {{f_time}}.</p>
{% endblock %}

Run Webpages in another machine:

To run server on different port:


python manage.py runserver <port>
Eg: python manage.py runserver 8001

To run on ip:

Register ip in allowed_hosts in settings.py


ALLOWED_HOSTS = ['192.168.60.143',]
To run server on system ip:
python manage.py runserver <ip>:<port>
Eg: python manage.py runserver 192.168.60.143:8010

3. Create another app (Person Details):

python manage.py startapp myapp

Register in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'timeapp',
'myapp',
]

Working with Models:


In app/models.py:

from django.db import models


import datetime

# Create your models here.


gender_list = [('M', 'Male'), ('F', 'Female')]

class Person(models.Model):
name = models.CharField(max_length=120)
gender = models.CharField(max_length=10, null=True, choices=gender_list)
birthday = models.DateField(default=datetime.datetime.now())
email = models.EmailField(max_length=120, unique=True)
url = models.URLField(max_length=120)
bio = models.TextField(max_length=420, blank=True)
photo = models.FileField(blank=True)

def __str__(self):
return "%s" % self.name

Migrations:

With the model created, the first thing we need to do is “initialize” our migrations.
Python manage.py makemigrations <app_name>

To view sql migration:


python manage.py sqlmigrate <appname> <migration no>

Then to apply the models (e.g., update the database) :


Python manage.py migrate

Insert and retrieve data from database using shell:

Open python shell using

python manage.py shell

Import Person model class


>>> from myapp.models import Person
Create an person object and save.
>>> person1 = Person(name="Sandeep", gender="M", email="sandeepbasva@gmail.com",
url="telugutoday.in")
>>> person1.save()
>>> person2 = Person(name="Nitya", gender="F", email="nitya@nitya.com",
url="telugutoday.in")
>>> person2.save()

OR

>>> Person.objects.create(name="Nitya", gender="F", email="nitya@nitya.com",


url="telugutoday.in")

To retrieve all persons:

>>> Person.objects.all()
<QuerySet [<Person: Sandeep>, <Person: Nitya>]>

To retrieve one person by name/id:

>>> person=Person.objects.get(id=1)
>>> person
<Person: Sandeep>

>>> person=Person.objects.get(name='Sandeep')
>>> person
<Person: Sandeep>
>>> person.name
'Sandeep'
>>> person.url
'telugutoday.in'

Update data:

>>> person.url='www.python.org'
>>> person.save()
>>> person=Person.objects.get(name='Sandeep')
>>> person.url
'www.python.org'

Filter data:

>>> Person.objects.filter(gender='M')
<QuerySet [<Person: Sandeep>]>

Count data:
>>> Person.objects.count()
2
Delete data:

person=Person.objects.get(name='Nitya')
>>> person.delete()
(1, {'myapp.Person': 1})
>>> Person.objects.all()
<QuerySet [<Person: Sandeep>]>

Admin site Interface:

Django comes with in-built admin site.

To create admin super user:


python manage.py createsuperuser

Give username , email id and password. Password must contain 8 characters.

Runserver and goto http://192.168.60.143:8000/admin/

The webpage is like these.

Enter the credentials and login. This page will display.


Register models with admin site:

Register the app in myapp/admin.py

from django.contrib import admin


from .models import Person

# Register your models here.

admin.site.register(Person)

Restart server and open admin page

Model will appears on admin page.


From the admin page you can add, modify, delete the objects.

Changing administration UI:

Simply change the site header and index_title

from django.contrib import admin


from .models import Person

# Register your models here.


admin.site.register(Person)

admin.site.site_header = 'Camp Site'


admin.site.index_title = 'Site Features Area'

Add media content:

Create media folder in inner project directory. i.e., camp/camp/media

Add media path in settings.py:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'camp/media')

Link media in urls.py

+static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)


from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
url(r'^admin/', admin.site.urls),

]+static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

Now we can add images to our objects.

GET objects from views:

In view.py:

"""This module contains business logic of our app,


It will communicate with database and templates"""
author = 'Sandeep Basva'
email = 'sandeepbasva@swecha.net'

from django.shortcuts import render


from django.http import HttpResponse
from .models import Person

# Create your views here.


def persons(request):
response = HttpResponse()
response.write('<html><body>')
response.write('<h1>Details</h1>')
person_list = Person.objects.all()
for person in person_list:
response.write('<li>%s%s</li>'%(person.id, person.name))
response.write("<a href='http://127.0.0.1:8000/persons/info/ %d'
>details"%person.id)

response.write('</body></html>')
return response

In urls.py:

from myapp.views import persons

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^person$', persons),

Get Details of specified Person:

In views.py:

def details(request,pid=0):
response = HttpResponse()
response.write('<html><body>')
try:
p=Person.objects.get(id=pid)
response.write('<h1>Details of %s</h1><hr>'%p.name)
response.write('<li>Gender: %s</li>'%p.gender)
response.write('<li>Birthday: %s</li>'%p.birthday)
response.write('<li>Favourite URL: %s</li>'%p.url)
response.write('<li>Message: %s</li>'%p.bio)
except Person.DoesNotExist:
print('The person details does not exist')
response.write('</body></html>')
return response

In urls.py:

from myapp.views import persons, details

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^persons$', persons),
url(r'^persons/info/(\d+)$', details),

]+static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Person details using templates:

Create a presentation file camp/camp/templates/person_details.html

<head>
<title>Information of {{p.name}}</title>
</head>
<body>
<table width=95%>
<tr>
<td width=50% bgcolor="blue">
<font size="8" color="white">Personal Information</font>
</td>
<td width=50% bgcolor="blue">
<font size="8" color="white">Contact Info</font>
</td>
</tr>
<tr>
<td bgcolor="lightblue">
<li>Name: {{p.name}}</li>
<li>Birthday: {{p.birthday}}</li>
<li>Gender: {{p.gender}}</li>
<li>Bio: {{p.bio}}</li>
</td>
<td bgcolor="violet">
<li>Email: {{p.email}}</li>
<li>Favourite website: {{p.url}}</li>
</td>
</tr>
</table>
</body>
</html>

In views.py change the details function:

from django.shortcuts import render, get_object_or_404

def details(request, pid=0):


p = get_object_or_404(Person, pk=pid)
return render(request, 'person_details.html', {'p': p})

URL is same, Then the ouut will be


Inheritance:

Create a base_person.html file:

<html>
<head>
<title>Information of {%block title%} {%endblock%}</title>
</head>
<body>
<table width=95%>
<tr>
<td width=50% bgcolor="blue">
<font size="8" color="white">Personal Information</font>
</td>
<td width=50% bgcolor="blue">
<font size="8" color="white">Contact Info</font>
</td>
</tr>
<tr>
{%block content%} {%endblock%}

</tr>
</table>
</body>
</html>

Create enherited person_details2.html file:

{%extends 'base_person.html'%}
{%block title %} {{p.name}} {%endblock%}
{%block content%}
<td bgcolor="lightblue">
<li>Name: {{p.name}}</li>
<li>Birthday: {{p.birthday}}</li>
<li>Gender: {{p.message}}</li>
<li>Message: {{p.bio}}</li>
</td>
<td bgcolor="violet">
<li>Email: {{p.email}}</li>
<li>Favourite website: {{p.url}}</li>
</td>
{%endblock%}
Add below lines to base_person.html file to get person image.
<td width=50% bgcolor="blue">
<font size="8" color="white">Its me...</font>
</td>

Add below lines to person_details2.html file to get person image.

<td>
<img src="{{p.photo.url}}" alt="My photo" width=300 height=250/>
</td>

Then go to this url: http://127.0.0.1:8000/persons/info/1/

Vous aimerez peut-être aussi