Sunteți pe pagina 1din 60

Django

Build an organized web application


Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Introduction
What is Django?
A high-level Python Web Framework
What is Django

 “Django is a high-level Python web framework that


encourages rapid development and clean, pragmatic
design.”
 Primary Focus
 Dynamic and database driven website
 Content based websites
Django History
 Named after famous Guitarist “Django Reinhardt”
 Developed by Adrian Holovaty & Jacob Kaplan-moss
 Open sourced in 2005
 1.0 Version released Sep.3 2008, now 2.14
Introduction
What is Framework?
Front-end & Back-end co-development
Introduction
What is Framework like?
A stage company for performers
Introduction
Why should I use Django?
Clean & Rapid development
Introduction
Who use Django?
Instagram & Pinterest & Bitbucket
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Outline
1. Introduction

2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Basic Knowledge
Basic Knowledge
Workflow
Web Browser

Template URL

View

Form

Model

Admin

Database
Basic Knowledge
Web Browser Web Browser
Template URL
• What users actually see
• Responds to what users do
View
when they
Form

Model 1. Click
2. Type
Admin
3. Press Enter
Database
Basic Knowledge
Web Browser URL
Template
• Often referred as the ‘web
URL
address’
View
• Provides mapping to View
Form

Model
What is mapping?
Admin The act of assigning
functions to URLs
Database
Basic Knowledge
Web Browser View
• Where all the functions are
Template URL
written
View
• Render content to Template
Form Get information from Model

Model before rendering content


• Put information into Model and
Admin
into Database through Form
Database
Basic Knowledge
Web Browser Template
• The place you systematically
Template URL
store all of your Html files
View
• You will have a ‘static’ folder to
Form store other CSS files,
Model Javascript files, or Images

Admin

Database
Basic Knowledge
Web Browser Form
Template URL HTML Form ≠ Django Form

View HTML Form


Form Consists of
• input element
Model • checkbox
• submit button
Admin
• radio button
Database and much more

Basic Knowledge
Web Browser Form
Template URL HTML Form ≠ Django Form

View Django Form


Form Aims to
• fetch data from html form
Model
• helps to connect to Model

Admin

Database
Basic Knowledge
Web Browser Model
• Describes the structure of an
Template URL
object you want to store in
View
Database
Form
• Goes straight to Database
Model and create & edit & request
Admin information as you wish
Database
Basic Knowledge
Web Browser Admin
Template URL
• Helps to register your object
in your Model so you can
View
manage data in Database
Form
• The registration has to be
Model
done in the first place
Admin

Database
Basic Knowledge
Web Browser Database
Template URL

View

Model
Form

Admin
?
Database
Basic Knowledge
Web Browser Database
Template URL

View

Form Collection of data


Model

Admin

Database
Basic Knowledge
Web Browser Database
• Collectionof data
Template URL

• Provided with a wonderful


View
back-end platform for easy
Form
management
Model

Admin

Database
Basic Knowledge
Workflow
Web Browser

Template URL

View

Form

Model

Admin

Database
Outline
1. Introduction
2. Basic Knowledge

3. Technical Details
4. Tutorial
5. Conclusion
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Directory Architecture
project_name/ ———————— Container of your entire project, which often referred as ‘workspace’
manage.py ————— The command-line utility to interact with your Django project
E.g1. python manage.py help E.g2. python manage.py runserver -h
your_project/ ———— The name of your Django project
inti .py ——- The file required for Python to treat this directory as a package
settings.py ——- Configuration for this Django project
url.py ————- Management of URLs to provide mapping to view.py

your_app/ —————- One of the web applications of this Django project


inti .py
migration/ ——- The file which stores all the variations in your database
static/ ———— The file which stores all of your CSS, JS, images
templates/ ——- The file which stores all of your Html
admin.py ——— It reads your model and provides interface to your database
form.py ———- It is used to fetch data and performs validation
model.py ——— Description of the format or structure of an object stored in Database
views.py ——— All the functions needed to process or respond user’s request
db.sqlite3 ——- Your database
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Module

mypackage/
init .py
mymodule.py

• A module is a python source file


• A package is a directory of Python module(s)
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Commands

$ django-admin startproject project_name


To start an project
Technical Details
Commands

$ python manage.py startapp app_name


To start an application
Technical Details
Commands

$ python manage.py createsuperuser


To create a superuser
Technical Details
Commands

$ python manage.py run server 0.0.0.0:8080


To start up your server

Note: 0.0.0.0:8080 —> address:port


Technical Details
Commands

$ python manage.py makemigrations


To create new migration based on the changes you
made in your models
$ python manage.py migrate
To apply migration into your database

Note: Migration is Django’s way of propagating the changes you made into your database schema
Technical Details
Commands

$ python manage.py -h
To ask for what kind of command can be used
$ python manage.py runserver -h
To ask for what kind of command can be used
after runserver
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Template Tags

{% for object in objects %}


{{ object.attribute }}
{% endfor %}

Django saves you the trouble of repeating your codes


Technical Details
Template Tags

{{ form.as_p }}

This is Django’s way of rendering Html Form

Note: Remember to wrap it within your HTML form tag


Technical Details
Template Tags

{{ csrf_token }}

This is used prevent ill-intentioned hacker from


hacking into your database

Note: Remember to wrap it within your HTML form tag


Django Project Level operations for Apps:

• Django-admin start project Mysite


• Python manage.py startapp polls
• Python manage.py runserver
• Python manage.py test.py
• Python manage.py collectstatic
• Python manage.py compilemessages
• Python manage.py makemigrations
• Python manage.py migrate
• Python manage.py
createsuperuser|changepassword|loaddata
Django as an MVC
Design Pattern
MVT Architecture:
 Models
Describes your data structure/database schema
 Views
Controls what a user sees
 Templates
How a user sees it
 Controller
The Django Framework
URL dispatcher
Model Overview
Model
class Category(models.Model):
name =
models.CharField(max_length=200) slug =
models.SlugField(unique=True)

class Entry(models.Model):
title =
models.CharField(max_length=200)
slug = models.SlugField(unique=True)
body = models.TextField()
data =models.DateTimeField(default=datetime.now)
categories = models.ManyToManyField(Category)
python manage.py syncdb
View

def entry_list(request):
entries = Ebtry.objects.all()[:5]
return render_to_response('list.html', {'entries': entries})

def entry_details(request, slug):


entry = get_object_or_404(Entry, slug = slug)
return render_to_response('details.html', {'entry': entry})
Template Syntax
 {{ variables }}, {% tags %}, filters (list.html)

<html>
<head>
<title>My Blog</title>
</head>
<body>
{% for entry in entries %}
<h1>{{ entry.title|upper }}</h1>
{{ entry.body }}<br/>
Published {{ entry.data|date:"d F Y" }},
<a href=”{{ entry.get_absolute_url }}”>link</a>.
{% endfor %}
</body>
</html>
Tag and Filter
 Build in Filters and Tags
 Custom tag and filter libraries
Put logic in tags

{% load comments %}
<h1>{{ entry.title|upper }}</h1>
{{ entry.body }}<br/>
Published {{ entry.data|date:"d F Y" }},
<a href=”{{ entry.get_absolute_url }}”>link</a>.
<h3> </h3>
{% get_comment_list for entry as comment_list %}
{% for comment in comment_list %}
{{ comment.content }}
{% endfor %}
Template Inheritance
base.html index.html
<html>
<head>
<title>
{% extend “base.html” %}
{% block title %}
{% block title %}
{% endblock %}
Main page
</title>
{% endblock %}
</head>
{% block body
<body>
%} Content
{% block body %}
{% endblock %}
{% endblock %}
</body>
</html>
URL Dispatcher
urlpatterns = patterns('',
#http://jianghu.leyubox.com/articles/
((r'^articles/$', ‘article.views.index'), )

#http://jianghu.leyubox.com/articles/2003/
(r'^articles/(?P<year>\d{4})/$', ‘article.views.year_archive'),

# http://jianghu.leyubox.com/articles/2003/ 12/
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$',
'article.views.month_archive'),

# http://jianghu.leyubox.com/articles/2003/ 12/3
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'article..
views.article_detail'), )
High-levelURL Configuration

url(r'^$', views.function)
?P< v > : to take v and sent to view as a variable
^ : beginning of the url
$ : end of the url
() : to capture part of the pattern
+ : to indicate the previous item should repeat at
least once
{} : to indicate a specific number of repetition
High-levelURL Configuration

url(r’^anything/(?P<variable>[0-9]+)/$’, views.function)

?P< v > : to take v and sent to view as a variable


^ : beginning of the url
$ : end of the url
() : to capture part of the pattern
+ : to indicate the previous item should repeat at
least once
{} : to indicate a specific number of repetition
High-levelURL Configuration

url(r'^(?P<variable>/[0-9]{n})/$', views.function)

?P< v > : to take v and sent to view as a variable


^ : beginning of the url
$ : end of the url
() : to capture part of the pattern
+ : to indicate the previous item should repeat at
least once
{} : to indicate a specific number of repetition
URL Dispatcher / Patterns
 Root URLshould be configured insettings.py
o ROOT_URLCONF ='app.urls'
 Syntax
patterns(prefix,
(regular expression, Python callback function [, optional dictionary [, optional name]])
)
Example:
urlpatterns = patterns(' ',
(r'^articles-year/$', 'mysite.news.views.articles_year'),
)

Note:
o No need to add a leading slash(/articles-year)
o The 'r' in front of each regular expression string is optional but recommended. It tells
Python that a
string is "raw" -- that nothing in the string should be escaped.
In python, the ‘\’ backslash character in control chars must be escaped for regular
expression use. Basically we have to add one more slash i.e \\t, \\b. To work around
backslash plague, you can raw string, by prefixing the string with the letter r.
56
 Can include other URLconf modules
urlpatterns = patterns(' ',
url(r'^support/', include('demoproject.support.urls')),
)
 Using Prefix
urlpatterns = patterns(' ',
(r'^articles/(\d{4})/$', 'mysite.news.views.articles_year'),
(r'^articles/(\d{4})/(\d{2})/$', 'mysite.news.views.articles_month'),
)
Here mysite.news.views is common, so can be rewritten as follows
urlpatterns = patterns('mysite.news.views',
(r'^articles/(\d{4})/$', 'articles_year'),
(r'^articles/(\d{4})/(\d{2})/$', 'articles_month'),
)
 Passing extra arguments and Dictionary mapping
patterns(' ',
(r'^articles/(?P<year>\d{4})/$', 'articles_year'), {'foo': 'bar'}),
)

We can get the values in views.py as year='2005', foo='bar'


57
Modules:Form
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)

<form action="/contact/" method="POST">


{{ form.as_table}}
<input type="submit" value="Submit" />
</form>
Modules:Adminstration
interface
Thank you

S-ar putea să vă placă și