SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
django workshop
Pierre Sudron (psudron@anevia.com)
Anevia
May 21, 2014
django : a short introduction
django is :
a python web framework
batteries included : ORM and DB migrations, template language,
cache, i18n, automatic admin pages, users and group management
DRY + KISS
If django doesn’t include a feature out of the box, it can be extended
with third-party extensions.
Workshop outline
We will discover some of the framework’s basics and see how to make a
blog engine with django :
MVT pattern and how django answers a request
designing the blog model entities
implementing some logic with views
displaying article and comments with templates
filling and validating forms
Part I:
django fundamentals
The MVT template
The Movel-View-Template pattern plays a central role in the
framework, every valid django application implements it.
Dive into models (1)
Model classes
Models are python classes that describe the database layout.
elements fetched from the database are instances of a model class
each attribute of the model represents a database column
An example with our blog’s Articles:
class Article(models.Model):
""" Blog article, has title, date, author and some content.
"""
title = models.CharField(’article title’, max_length=200)
author = models.ForeignKey(User)
pub_date = models.DateTimeField(’date published’)
content = models.TextField(’article content’)
Don’t forget : model classes must inherit from models.Model
Dive into models (2)
Models are ”synced” with the database, our Article class will generate
the following SQL :
CREATE TABLE "blog_article" (
"id" integer NOT NULL PRIMARY KEY,
"title" varchar(200) NOT NULL,
"author_id" integer NOT NULL REFERENCES "auth_user" ("id"),
"pub_date" datetime NOT NULL,
"content" text NOT NULL,
);
Take control with views
Views (classes or functions)
Views are the entry point of HTTP requests.
queries data from the DB, validates forms
returns rendered templates using collected data
def home(request):
""" Blog homepage.
"""
articles = Article.objects.all().order_by(’-pub_date’)
return render(request, ’blog_home.html’,
{
’articles’: articles,
})
Shape you centent with templates
Template files
Canvases that are used to generate pages with data provided by the
calling view
insert data, make DB queries (to some extent)
filters, tests, iterate over collections
template inheritance
{% extends "base.html" %}
{% block content %}
{% for article in articles %}
<div class="blog-post">
<h2>{{ article.title }} </h2>
<p>{{ article.pub_date }} by {{ article.author }} </p>
<p>{{ article.content }} </p>
</div>
{% endfor %}
{% endblock %}
Dispatching requests with patterns
url(r’^$’, ’blog.views.home’),
url(r’^article/(?P<article_id>w+)/$’, ’blog.views.view_article’),
Request handling with django : the full cycle
Part II:
let’s build a blog
First : let’s design the model
Weed need several entities to make a blog. Translating this
representation is straightforward.
Articles
Comments
Users
ArticleTags
Models (1/3) : Article
unique id (auto)
title
author (User object
provided)
publication date
content
tags
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(’article title’,
max_length=200)
author = models.ForeignKey(User)
pub_date = models.DateTimeField(
’date published’,
auto_now_add=True)
content = models.TextField(’content’)
tags = models.ManyToManyField(ArticleTag,
blank=True)
Models (2/3) : Comment
unique id (auto)
author name
parent Article
publication date
content
class Comment(models.Model):
author = models.CharField(’author name’,
max_length=100)
article = models.ForeignKey(Article)
pub_date = models.DateTimeField(
’date published’,
auto_now_add=True)
content = models.TextField(’comment’)
Models (3/3) : Article tag
unique id (auto)
tag name
class ArticleTag(models.Model):
tag_title = models.CharField(’tag title’,
max_length=30)
The article/tag relationship was added in the Article class, not need to
add it twice.
Model fields
integers
note = models.IntegerField(’just an int’)
number_nodes = models.PositiveIntegerField(’always be positive!’)
over9000 = models.BigIntegerField(’8 bytes integer’)
stings and text
title = models.CharField(’rather small string’, max_length=100)
content = models.TextField(’you can write your biography here’)
url = models.URLField(’some website’)
mailing = models.EmailField(’valid email address’)
time
birthday = models.DateField(’just the date’)
timestamp = models.DateTimeField(’down to microseconds’)
files
file = models.FileField(upload_to=’tmp_folder’)
lolcat = models.ImageField(upload_to=’img/cats/’)
Relationship fields
foreign key (many to one)
com_parent_article = models.ForeignKey(Article)
many to many
article_tags = models.ManyToManyField(ArticleTags)
one to one
secret_identity = models.OneToOneField(Superhero)
Smarter models
Validators can help keep logic inside models:
from django.core.exceptions import ValidationError
def loves_pizza(user):
if not user.loves_pizza:
raise ValidationError(u’How can one not love pizza?’)
class PizzaFanMembership(object):
user = models.ForeignKey(User, validators=[loves_pizza])
limit values range (kinda enum-like)
TOPPINGS = ( (0, ’none’),
(1, ’mushrooms’), (2, ’pepper’), ... )
pizza_topping = models.PositiveIntegerField(choices=TOPPINGS)
custom field types (eg. MarkdownTextField)
SQL-like constrains (not blank, defaults, etc.)
Back the blog : automatic admin pages !
Admin pages are generated from the model classes and give you complete
CRUD functions with no sweat :
Part III:
display our blog
Display data with views
Views (classes or functions)
Views are the entry point of HTTP requests.
queries data from the DB, validates forms
returns rendered templates using collected data
Roughly :
one page = one view
We will need 3 views for our blog :
”homepage” displaying all the articles (most recent first)
detailed view showing and article with all its comments
tag list page showing tag usage statistics
Homepage view
def home(request):
""" Blog homepage.
"""
articles = Article.objects.all().order_by(’-pub_date’)
return render(request, ’blog_home.html’,
{
’articles’: articles,
})
this view has no parameter other than the mandatory request
parameter
request constains a lot of useful stuff like sessions, POST, GET...
articles is a QuerySet and supports many SQL-like methods :
count, get, filter, exclude, contains, comparisons...
render generates the html page from a template and with a
context containing the articles QuerySet
Article view
def view_article(request, article_id):
""" View a specific article.
"""
article = get_object_or_404(Article, id=article_id)
comments = Comment.objects.filter(article=article).order_by(
’pub_date’)
return render(request, "blog_article.html",
{
’article’: article,
’comments’: comments,
})
get object or 404 is a shortcut function
notice how the comparison inside filter acts like a WHERE clause
oder by ’row’ is DESC, whereas -’row’ is ASC
a QuerySet can be a collection (comments) as well as a single item
(article)
Article view : which article by the way ?
Besides request, the view requires a article id parameter.
def view_article(request, article_id):
This id comes from the requested url, parsed by the url pattern :
url(r’^article/(?P<article_id>w+)/$’, ’blog.views.view_article’),
Mind that the parameter inside the url pattern and in the function
prototype must be the same !
Parameter’s order doesn’t matter though.
Beyond the render call
Template files
Canvases that are used to generate pages with data provided by the
calling view.
Templates can use data provided in the context dict, using item keys.
return render(request,
"blog_article.html",
{
’article’: article,
’comments’: comments,
})
In the blog article.html template,
we will be able to access :
article : the Article model
comments : the list of related
Comment objects
Templating (1)
insert values
<h2>{{ article.title }} </h2>
<p>{{ article.pub_date }} by {{ article.author }} </p>
use filters
{{ article.pub_date | date:"D d M Y" }}
{{ article.content | truncatewords:150 }}
{{ boolean | yesno:"yeah,no,maybe" }}
perform tests
{% if user.height < 1.5 %}
<p>You must be 1.5m to enter</p>
{% endif %}
loop over iterables
{% for comment in comments %}
<p>{{ comment.author }} : {{ comment.content }}
{% endfor %}
Templating (2)
template inheritance
<!-- base.html --> Some stuff around...
{% block footer %}
<!-- but no footer ! -->
{% endblock %}
<!-- other_page.html -->
{% extends base.html %}
{% block footer %}
Redefined footer ! This is fancier isn’t it ?
{% endblock %}
reverse urls (this is a killer feature !)
<a href="{% url ’blog.views.article’ article.id %} ">
Read the article {{ article.title }}
</a>
Example : complete article template
{% extends "base.html" %}
{% block content %}
<h2>{{ article.title }} </h2>
<p>{{ article.pub_date }} by {{ article.author }} </p>
<p>
{% for tag in article.tags.all %} {{ tag }} , {% endfor %}
</p>
<p>{{ article.content }} </p>
<hr>
<h2>Comments</h2>
{% for comment in comments %}
<div class="comment">
<h5>{{ comment.author }} </h5>
<p>{{ comment.pub_date }} </p>
<p>{{ comment.content }} </p>
</div>
{% endfor %}
{% endblock %}
Part III:
add, modify and delete content
Delete an article
Some views can be used to perform a specific task and then redirect.
def delete_article(request, article_id):
""" Delete an article given its ID.
"""
article = get_object_or_404(Article, id=article_id)
article.delete()
return redirect(’blog.views.home’)
Add an url pattern and it’s ready to use.
url(r’^delete/(?P<article_id>w+)/$’, ’blog.views.delete_article’),
<a href="{% url ’blog.views.delete_article’ article.id %} ">
Click to delete article {{ article }}
</a>
Form classes
To create new model objects or edit existing ones, we need to use Forms.
custom forms
class ContactForm(forms.Form):
sender = forms.EmailField()
message = forms.CharField()
models forms generated from your models
from .models import Article
class ArticleForm(forms.ModelForm):
""" Article creation or edition form.
"""
class Meta:
model = Article
fields = (’title’, ’content’)
Model forms use validation mechanisms defined inside the model.
Use a form to create an item
Forms are managed inside views.
def create_article(request):
""" Write a new blog article.
"""
edition_form = ArticleForm(request.POST or None)
if edition_form.is_valid():
# creating an article and setting its author
article = edition_form.save(commit=False)
article.author = request.user
article.save()
# redirect to the newly created article
return redirect(’blog.views.view_article’,
article_id=article.id)
# render the edition form if the data is blank or invalid
return render(request, "edit_article.html",
{
’form’: edition_form,
})
Display forms inside templates
the ”quick and dirty” way
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Save</button>
<a class="btn btn-default" href="{% url ’blog.views.home’ %} ">
Cancel
</a>
</form>
custom field-by-field way
{% csrf_token %}
{% for field in form %}
<label for={{ field.auto_id }} >{{ field.label }} </label>
{{ field }}
{% endfor %}
Edit an existing item
The same ModelForm can be used for item edition :
def edit_article(request, article_id=None):
""" Edit a blog article.
"""
article = get_object_or_404(Article, id=article_id)
edition_form = ArticleForm(request.POST or None, instance=article)
if edition_form.is_valid():
# saving the edited article
edition_form.save()
return redirect(’blog.views.view_article’, article_id=article.id)
# render the edition form if the data is blank or invalid
return render(request, "edit_article.html",
{
’form’: edition_form,
})
Part IV:
what’s next?
But there’s more !
migration: migrates the database when model classes are modified
authentication: built-in user objects, groups, session management
protect your views
@permission_required(’blog.edit_comment’)
def moderation_view(request):
...
painless caching
cache views
@cache_page(60 * 15)
def view_with_many_queries(request):
...
cache template blocks
{% cache 500 sidebar %}
.. sidebar ..
{% endcache %}
unit testing, XSS protection, flatpages...
NIH & DRY
If you’re in need for feature, first check if it not already available :
the framework has a lot of features and ready to use tools
if the framework doesn’t provide you with what you need, look at
the many great extensions available (image caching and resizing,
REST framework, LDAP, benchmarking. etc)
Django is all about keeping it simple, being productive while still making
reliable software.
Documentation & resources
official documentation : https://docs.djangoproject.com
Two scoops of django by Daniel Greenfeld and Audrey Roy
Thank you!
Any questions?

Mais conteúdo relacionado

Mais procurados

jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginnersSpin Lai
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue AdventureAllegient
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryZeeshan Khan
 
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...Atlassian
 
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...Atlassian
 
Introduction to whats new in css3
Introduction to whats new in css3Introduction to whats new in css3
Introduction to whats new in css3Usman Mehmood
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScriptLilia Sfaxi
 
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...David Glick
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do MoreRemy Sharp
 

Mais procurados (20)

Learn css3
Learn css3Learn css3
Learn css3
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery
jQueryjQuery
jQuery
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginners
 
Handlebars.js
Handlebars.jsHandlebars.js
Handlebars.js
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Polymer
PolymerPolymer
Polymer
 
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
 
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Introduction to whats new in css3
Introduction to whats new in css3Introduction to whats new in css3
Introduction to whats new in css3
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
Integrating Plone with E-Commerce and Relationship Management: A Case Study i...
 
Jsp1
Jsp1Jsp1
Jsp1
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
Jquery 2
Jquery 2Jquery 2
Jquery 2
 

Destaque

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Django shop
Django shopDjango shop
Django shopTribaal
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and AnswersPython Devloper
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Multi Tenancy With Python and Django
Multi Tenancy With Python and DjangoMulti Tenancy With Python and Django
Multi Tenancy With Python and Djangoscottcrespo
 
Big o notation
Big o notationBig o notation
Big o notationkeb97
 
Django CMS & Integrating it with django shop
Django CMS & Integrating it with django shopDjango CMS & Integrating it with django shop
Django CMS & Integrating it with django shopMindfire Solutions
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best PracticesDavid Arcos
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application FrameworkSimon Willison
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 

Destaque (15)

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
dJango
dJangodJango
dJango
 
Django shop
Django shopDjango shop
Django shop
 
Django in Windows
Django in WindowsDjango in Windows
Django in Windows
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and Answers
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Multi Tenancy With Python and Django
Multi Tenancy With Python and DjangoMulti Tenancy With Python and Django
Multi Tenancy With Python and Django
 
Big o notation
Big o notationBig o notation
Big o notation
 
Django Models
Django ModelsDjango Models
Django Models
 
Django CMS & Integrating it with django shop
Django CMS & Integrating it with django shopDjango CMS & Integrating it with django shop
Django CMS & Integrating it with django shop
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with Data
 

Semelhante a Django workshop : let's make a blog

Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress WebsitesKyle Cearley
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheetLam Hoang
 
Templates
TemplatesTemplates
Templatessoon
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxsalemsg
 
Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]Victor Miclovich
 

Semelhante a Django workshop : let's make a blog (20)

Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
 
Templates
TemplatesTemplates
Templates
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
 
Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]Django Girls Mbale [victor's sessions]
Django Girls Mbale [victor's sessions]
 

Último

Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectssuserb6619e
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectErbil Polytechnic University
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 

Último (20)

Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction Project
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 

Django workshop : let's make a blog

  • 1. django workshop Pierre Sudron (psudron@anevia.com) Anevia May 21, 2014
  • 2. django : a short introduction django is : a python web framework batteries included : ORM and DB migrations, template language, cache, i18n, automatic admin pages, users and group management DRY + KISS If django doesn’t include a feature out of the box, it can be extended with third-party extensions.
  • 3. Workshop outline We will discover some of the framework’s basics and see how to make a blog engine with django : MVT pattern and how django answers a request designing the blog model entities implementing some logic with views displaying article and comments with templates filling and validating forms
  • 5. The MVT template The Movel-View-Template pattern plays a central role in the framework, every valid django application implements it.
  • 6. Dive into models (1) Model classes Models are python classes that describe the database layout. elements fetched from the database are instances of a model class each attribute of the model represents a database column An example with our blog’s Articles: class Article(models.Model): """ Blog article, has title, date, author and some content. """ title = models.CharField(’article title’, max_length=200) author = models.ForeignKey(User) pub_date = models.DateTimeField(’date published’) content = models.TextField(’article content’) Don’t forget : model classes must inherit from models.Model
  • 7. Dive into models (2) Models are ”synced” with the database, our Article class will generate the following SQL : CREATE TABLE "blog_article" ( "id" integer NOT NULL PRIMARY KEY, "title" varchar(200) NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id"), "pub_date" datetime NOT NULL, "content" text NOT NULL, );
  • 8. Take control with views Views (classes or functions) Views are the entry point of HTTP requests. queries data from the DB, validates forms returns rendered templates using collected data def home(request): """ Blog homepage. """ articles = Article.objects.all().order_by(’-pub_date’) return render(request, ’blog_home.html’, { ’articles’: articles, })
  • 9. Shape you centent with templates Template files Canvases that are used to generate pages with data provided by the calling view insert data, make DB queries (to some extent) filters, tests, iterate over collections template inheritance {% extends "base.html" %} {% block content %} {% for article in articles %} <div class="blog-post"> <h2>{{ article.title }} </h2> <p>{{ article.pub_date }} by {{ article.author }} </p> <p>{{ article.content }} </p> </div> {% endfor %} {% endblock %}
  • 10. Dispatching requests with patterns url(r’^$’, ’blog.views.home’), url(r’^article/(?P<article_id>w+)/$’, ’blog.views.view_article’),
  • 11. Request handling with django : the full cycle
  • 13. First : let’s design the model Weed need several entities to make a blog. Translating this representation is straightforward. Articles Comments Users ArticleTags
  • 14. Models (1/3) : Article unique id (auto) title author (User object provided) publication date content tags from django.contrib.auth.models import User class Article(models.Model): title = models.CharField(’article title’, max_length=200) author = models.ForeignKey(User) pub_date = models.DateTimeField( ’date published’, auto_now_add=True) content = models.TextField(’content’) tags = models.ManyToManyField(ArticleTag, blank=True)
  • 15. Models (2/3) : Comment unique id (auto) author name parent Article publication date content class Comment(models.Model): author = models.CharField(’author name’, max_length=100) article = models.ForeignKey(Article) pub_date = models.DateTimeField( ’date published’, auto_now_add=True) content = models.TextField(’comment’)
  • 16. Models (3/3) : Article tag unique id (auto) tag name class ArticleTag(models.Model): tag_title = models.CharField(’tag title’, max_length=30) The article/tag relationship was added in the Article class, not need to add it twice.
  • 17. Model fields integers note = models.IntegerField(’just an int’) number_nodes = models.PositiveIntegerField(’always be positive!’) over9000 = models.BigIntegerField(’8 bytes integer’) stings and text title = models.CharField(’rather small string’, max_length=100) content = models.TextField(’you can write your biography here’) url = models.URLField(’some website’) mailing = models.EmailField(’valid email address’) time birthday = models.DateField(’just the date’) timestamp = models.DateTimeField(’down to microseconds’) files file = models.FileField(upload_to=’tmp_folder’) lolcat = models.ImageField(upload_to=’img/cats/’)
  • 18. Relationship fields foreign key (many to one) com_parent_article = models.ForeignKey(Article) many to many article_tags = models.ManyToManyField(ArticleTags) one to one secret_identity = models.OneToOneField(Superhero)
  • 19. Smarter models Validators can help keep logic inside models: from django.core.exceptions import ValidationError def loves_pizza(user): if not user.loves_pizza: raise ValidationError(u’How can one not love pizza?’) class PizzaFanMembership(object): user = models.ForeignKey(User, validators=[loves_pizza]) limit values range (kinda enum-like) TOPPINGS = ( (0, ’none’), (1, ’mushrooms’), (2, ’pepper’), ... ) pizza_topping = models.PositiveIntegerField(choices=TOPPINGS) custom field types (eg. MarkdownTextField) SQL-like constrains (not blank, defaults, etc.)
  • 20. Back the blog : automatic admin pages ! Admin pages are generated from the model classes and give you complete CRUD functions with no sweat :
  • 22. Display data with views Views (classes or functions) Views are the entry point of HTTP requests. queries data from the DB, validates forms returns rendered templates using collected data Roughly : one page = one view We will need 3 views for our blog : ”homepage” displaying all the articles (most recent first) detailed view showing and article with all its comments tag list page showing tag usage statistics
  • 23. Homepage view def home(request): """ Blog homepage. """ articles = Article.objects.all().order_by(’-pub_date’) return render(request, ’blog_home.html’, { ’articles’: articles, }) this view has no parameter other than the mandatory request parameter request constains a lot of useful stuff like sessions, POST, GET... articles is a QuerySet and supports many SQL-like methods : count, get, filter, exclude, contains, comparisons... render generates the html page from a template and with a context containing the articles QuerySet
  • 24. Article view def view_article(request, article_id): """ View a specific article. """ article = get_object_or_404(Article, id=article_id) comments = Comment.objects.filter(article=article).order_by( ’pub_date’) return render(request, "blog_article.html", { ’article’: article, ’comments’: comments, }) get object or 404 is a shortcut function notice how the comparison inside filter acts like a WHERE clause oder by ’row’ is DESC, whereas -’row’ is ASC a QuerySet can be a collection (comments) as well as a single item (article)
  • 25. Article view : which article by the way ? Besides request, the view requires a article id parameter. def view_article(request, article_id): This id comes from the requested url, parsed by the url pattern : url(r’^article/(?P<article_id>w+)/$’, ’blog.views.view_article’), Mind that the parameter inside the url pattern and in the function prototype must be the same ! Parameter’s order doesn’t matter though.
  • 26. Beyond the render call Template files Canvases that are used to generate pages with data provided by the calling view. Templates can use data provided in the context dict, using item keys. return render(request, "blog_article.html", { ’article’: article, ’comments’: comments, }) In the blog article.html template, we will be able to access : article : the Article model comments : the list of related Comment objects
  • 27. Templating (1) insert values <h2>{{ article.title }} </h2> <p>{{ article.pub_date }} by {{ article.author }} </p> use filters {{ article.pub_date | date:"D d M Y" }} {{ article.content | truncatewords:150 }} {{ boolean | yesno:"yeah,no,maybe" }} perform tests {% if user.height < 1.5 %} <p>You must be 1.5m to enter</p> {% endif %} loop over iterables {% for comment in comments %} <p>{{ comment.author }} : {{ comment.content }} {% endfor %}
  • 28. Templating (2) template inheritance <!-- base.html --> Some stuff around... {% block footer %} <!-- but no footer ! --> {% endblock %} <!-- other_page.html --> {% extends base.html %} {% block footer %} Redefined footer ! This is fancier isn’t it ? {% endblock %} reverse urls (this is a killer feature !) <a href="{% url ’blog.views.article’ article.id %} "> Read the article {{ article.title }} </a>
  • 29. Example : complete article template {% extends "base.html" %} {% block content %} <h2>{{ article.title }} </h2> <p>{{ article.pub_date }} by {{ article.author }} </p> <p> {% for tag in article.tags.all %} {{ tag }} , {% endfor %} </p> <p>{{ article.content }} </p> <hr> <h2>Comments</h2> {% for comment in comments %} <div class="comment"> <h5>{{ comment.author }} </h5> <p>{{ comment.pub_date }} </p> <p>{{ comment.content }} </p> </div> {% endfor %} {% endblock %}
  • 30. Part III: add, modify and delete content
  • 31. Delete an article Some views can be used to perform a specific task and then redirect. def delete_article(request, article_id): """ Delete an article given its ID. """ article = get_object_or_404(Article, id=article_id) article.delete() return redirect(’blog.views.home’) Add an url pattern and it’s ready to use. url(r’^delete/(?P<article_id>w+)/$’, ’blog.views.delete_article’), <a href="{% url ’blog.views.delete_article’ article.id %} "> Click to delete article {{ article }} </a>
  • 32. Form classes To create new model objects or edit existing ones, we need to use Forms. custom forms class ContactForm(forms.Form): sender = forms.EmailField() message = forms.CharField() models forms generated from your models from .models import Article class ArticleForm(forms.ModelForm): """ Article creation or edition form. """ class Meta: model = Article fields = (’title’, ’content’) Model forms use validation mechanisms defined inside the model.
  • 33. Use a form to create an item Forms are managed inside views. def create_article(request): """ Write a new blog article. """ edition_form = ArticleForm(request.POST or None) if edition_form.is_valid(): # creating an article and setting its author article = edition_form.save(commit=False) article.author = request.user article.save() # redirect to the newly created article return redirect(’blog.views.view_article’, article_id=article.id) # render the edition form if the data is blank or invalid return render(request, "edit_article.html", { ’form’: edition_form, })
  • 34. Display forms inside templates the ”quick and dirty” way <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Save</button> <a class="btn btn-default" href="{% url ’blog.views.home’ %} "> Cancel </a> </form> custom field-by-field way {% csrf_token %} {% for field in form %} <label for={{ field.auto_id }} >{{ field.label }} </label> {{ field }} {% endfor %}
  • 35. Edit an existing item The same ModelForm can be used for item edition : def edit_article(request, article_id=None): """ Edit a blog article. """ article = get_object_or_404(Article, id=article_id) edition_form = ArticleForm(request.POST or None, instance=article) if edition_form.is_valid(): # saving the edited article edition_form.save() return redirect(’blog.views.view_article’, article_id=article.id) # render the edition form if the data is blank or invalid return render(request, "edit_article.html", { ’form’: edition_form, })
  • 37. But there’s more ! migration: migrates the database when model classes are modified authentication: built-in user objects, groups, session management protect your views @permission_required(’blog.edit_comment’) def moderation_view(request): ... painless caching cache views @cache_page(60 * 15) def view_with_many_queries(request): ... cache template blocks {% cache 500 sidebar %} .. sidebar .. {% endcache %} unit testing, XSS protection, flatpages...
  • 38. NIH & DRY If you’re in need for feature, first check if it not already available : the framework has a lot of features and ready to use tools if the framework doesn’t provide you with what you need, look at the many great extensions available (image caching and resizing, REST framework, LDAP, benchmarking. etc) Django is all about keeping it simple, being productive while still making reliable software.
  • 39. Documentation & resources official documentation : https://docs.djangoproject.com Two scoops of django by Daniel Greenfeld and Audrey Roy