Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Introduction to Django
Search
Kien Nguyen
October 05, 2013
Technology
120
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Introduction to Django
Django and Heroku
Kien Nguyen
October 05, 2013
More Decks by Kien Nguyen
See All by Kien Nguyen
Introduction
kiennt
0
63
Facebook Login Security
kiennt
0
60
Introduction to Django v2
kiennt
0
120
Clean code
kiennt
8
430
Unix_Process.pdf
kiennt
2
8.3k
Happiness
kiennt
1
480
RTMP and RTMPE protocols
kiennt
2
680
Other Decks in Technology
See All in Technology
JavaScript 研修 (2026)
recruitengineers
PRO
2
530
Master Dataグループ紹介資料
sansan33
PRO
1
4.8k
20260807_第6回_関東kaggler会LT_claw系bot xangiと始める、"寂しくない" kaggle
sugupoko
0
270
モノリス Rails でも日中に rails db:migrate を走らせたい! / Daytime rails db:migrate on Monolithic Rails!
euglena1215
4
580
[ChatGPT Work LT]事務作業が苦手な人のための バックオフィスの「半」自動化
chimaki_iot
0
280
今こそ聞きたいソフトウェア設計 ドメイン駆動設計再入門
masuda220
PRO
17
7.2k
ブラウザ研修 2026
recruitengineers
PRO
6
980
ボトムアップ文化が強い組織で セキュリティをどう根付かせていくかの現在進行形の話 / Making Security Stick in a Bottom-Up Organization
yamaguchitk333
0
220
LanceDB入門
mocobeta
7
460
認知負荷をGemini で溶かす — GKE 基盤「Orbit」における AI エージェントの実践
sansantech
PRO
1
290
制約理論(ToC)入門 2026版
recruitengineers
PRO
8
2.2k
【CEDEC2026】グラフィックスエンジニアのためのニューラルシェーディング入門
cygames
PRO
0
140
Featured
See All Featured
Digital Ethics as a Driver of Design Innovation
axbom
PRO
1
360
Art, The Web, and Tiny UX
lynnandtonic
304
22k
Intergalactic Javascript Robots from Outer Space
tanoku
273
27k
Joys of Absence: A Defence of Solitary Play
codingconduct
1
430
Data-driven link building: lessons from a $708K investment (BrightonSEO talk)
szymonslowik
1
1.2k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
590
How STYLIGHT went responsive
nonsquared
100
6.2k
Building Applications with DynamoDB
mza
96
7.2k
AI in Enterprises - Java and Open Source to the Rescue
ivargrimstad
0
1.4k
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
66
57k
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
210
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
5
1.2k
Transcript
Introduction to Django Kien Nguyen Trung
Kien Nguyen Trung github.com/kiennt kiennt.com
What is django
Django is high-level Python Web framework that encourages rapid development
and clean, pragmatics design.
Philosophy Rapid Development Loosely coupled Reusable Applications Dont Repeat Yourself
(DRY)
Django sites instagram.com pinterest.com disqus.com bitbucket.com rdio.com addons.mozilla.org
Features Object Relational Mapping (ORM) Automatic admin interface Elegent URL
design Template system
Architecture
Model - View - Template Model - what things are
View - how things are processed Template - How things are presented
Models import datetime from django.db import models from django.utils import
timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
Represents the DB objects BEGIN; CREATE TABLE "codecamp_question" ( "id"
integer NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL ) ; CREATE TABLE "codecamp_choice" ( "id" integer NOT NULL PRIMARY KEY, "question_id" integer NOT NULL REFERENCES "codecamp_question" ("id"), "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ) ; COMMIT;
ORM latest_question_list = Question.objects.order_by('-pub_date')[:5] q = Question.objects.get(pk=question_id) selected_choice = q.choice_set.get(pk=choice_id)
selected_choice.votes += 1 selected_choice.save() Never write SQL - unless you really need
Views Where all magic happens Normally Keep your logic in
the model Process model instances Render HTML
Views def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice
= p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('results', args=(p.id,)))
Templates Separate design from code Separate designer from code Separate
design from developers
index.html {% if latest_question_list %} <ul> {% for question in
latest_question_list %} <li> <a href="{% url 'detail' question.id %}"> {{ question.question_text }} </a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect,
HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context)
detail.html <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message
}}</strong></p> {% endif %} <form action="{% url 'vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}"> {{ choice.choice_text }} </label><br /> {% endfor %} <input type="submit" value="Vote" /> </form>
views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect,
HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question': question })
Security advantages No raw SQL from users - we deal
with models and queries Automatic HTML parsing - no XSS attacks CSRF protection - no replay of forms by other code
URLs from django.conf.urls import patterns, include, url from codecamp import
views # for admin page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^polls/(?P<question_id>\d+)/$', views.detail, name='detail'), url(r'^polls/(?P<question_id>\d+)/results/$', views.results, name='results'), url(r'^polls/(?P<question_id>\d+)/vote/$', views.vote, name='vote'), url(r'^admin/', include(admin.site.urls)), ) URLs map to views (view Regular expressions)
http://example.com/ http://example.com/polls/1 http://example.com/polls/1/result http://example.com/polls/1/vote
Views are python function from django.shortcuts import render, get_object_or_404 from
django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question': question })
Admin interface class ChoiceInline(admin.StackedInline): model = models.Choice extra = 4
class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date']}), ] search_fields = ['question_text'] list_display = ('question_text', 'pub_date', 'was_published_recently') inlines = [ChoiceInline] admin.site.register(models.Question, QuestionAdmin)
Admin interface class MemberAdmin(UserAdmin): list_filter = ('is_admin', ) filter_horizontal =
() fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email', )}), ) search_fields = ('email', 'username') list_display = ('username', 'email', 'is_admin', 'date_joined') list_per_page = 50 admin.site.register(models.Member, MemberAdmin) admin.site.register(models.Question, QuestionAdmin)
Other features Forms Generic Views User management Advance queries
manage.py shell: start up a python shell with your django
project loaded in test: run you unit test runserver: run built in server for python app syncdb: create SQL for your models
Heroku
Features Support various programming language: Python, Ruby, Node.js, Java, Scala,
... Support a lot of plugins to work with other cloud services (AWS, RDS, MongoDB, ...) Painless deploy/rollback over git tool Easily to scale horizontally???
addons.heroku.com Worker hours Email services HTTPs Databases Message/Task Queue
Django over Heroku Procfile gunicorn requirements.txt
requirements.txt Django==1.5.1 dj-database-url==0.2.1 dj-static==0.0.5 gunicorn==17.5 psycopg2==2.5.1 static==0.4
Procfile web: gunicorn codecamp.wsgi
QA
References https://www.heroku.com/ https://www.djangoproject.com/ https://speakerdeck.com/kiennt/introduction-to- django