SlideShare a Scribd company logo
1 of 4
Download to read offline
Django Cheat Sheet
Django is a high-level Python Web framework that encourages rapid development
and clean, pragmatic design.
by lam
󰅂Starting a Project
Create a virtual environment
$ virtualenv venv
$ source venv/bin/activ
ate
Install Django
$ pip install Django
Setup Django Project
$ django-admin.py start
project projectname
Create database
$ python manage.py sync
db
Run Server
$ python manage.py runs
erver
Create App
$ python manage.py star
tapp appname
Add to INATALLED_APPS list
Create Templates
$ mkdir appname/templat
es
󰅂
Working with
Model
De ning a model
To de ne the models for your
app, modify the le
models.py that was created
in your app’s folder. The
__str__() method tells Django
how to represent data
objects based on this model.
from django.db import m
odels
class Topic(models.Mode
l):
"""A topic the user i
s learning about."""
text = models.CharFie
ld(max_length=200)
date_added = models.D
ateTimeField(
auto_now_add=True)
def __str__(self):
return self.text
Activating a model
To use a model the app must
be added to the tuple
INSTALLED_APPS, which is
stored in the project’s
settings.py le.
INSTALLED_APPS = (
--snip--
'django.contrib.stati
cfiles',
# My apps
'learning_logs',
)
Migrating the database
The database needs to be
modi ed to store the kind of
󰅂
Building a simple
homepage
Users interact with a project
through web pages, and a
project’s home page can
start out as a simple page
with no data. A page usually
needs a URL, a view, and a
template.
Mapping a project’s URLs
The project’s main urls.py le
tells Django where to nd the
urls.py les associated with
each app in the project
from django.conf.urls i
mport include, url
from django.contrib imp
ort admin
urlpatterns = [
url(r'^admin/', inclu
de(admin.site.urls)),
url(r'', include('lea
rning_logs.urls',
namespace='learning_l
ogs')),
]
Mapping an app’s URLs
An app’s urls.py le tells
Django which view to use for
each URL in the app. You’ll
need to make this le
yourself, and save it in the
app’s folder.
from django.conf.urls i
mport url
from . import views
urlpatterns = [
url(r'^$', views.inde
x, name='index'),
]
󰅂Another model
A new model can use an
existing model. The
ForeignKey attribute
establishes a connection
between instances of the
two related models. Make
󰏪
󰅢
data that the model
represents.
$ python manage.py make
migrations learning_log
s
$ python manage.py migr
ate
Creating a superuser
A superuser is a user account
that has access to all aspects
of the project.
$ python manage.py crea
tesuperuser
Registering a model
You can register your models
with Django’s admin site,
which makes it easier to work
with the data in your project.
To do this, modify the app’s
admin.py le. View the admin
site at
http://localhost:8000/admin/.
from django.contrib imp
ort admin
from learning_logs.mode
ls import Topic
admin.site.register(Top
ic)
Writing a simple view
A view takes information
from a request and sends
data to the browser, often
through a template. View
functions are stored in an
app’s views.py le. This
simple view function doesn’t
pull in any data, but it uses
the template index.html to
render the home page
from django.shortcuts i
mport render
def index(request):
"""The home page for
Learning Log."""
return render(reques
t, 'learning_logs/inde
x.html')
Writing a simple template
A template sets up the
structure for a page. It’s a mix
of html and template code,
which is like Python but not
as powerful. Make a folder
called templates inside the
project folder. Inside the
templates folder make
another folder with the same
name as the app. This is
where the template les
should be saved
<p>Learning Log</p>
<p>Learning Log helps y
ou keep track of your
learning, for any topi
c you're learning
about.</p>
sure to migrate the
database after adding a new
model to your app.
De ning a model with a
foreign key
class Entry(models.Mode
l):
"""Learning log entrie
s for a topic."""
topic = models.Foreig
nKey(Topic)
text = models.TextFie
ld()
date_added = models.D
ateTimeField(
auto_now_add=True)
def __str__(self):
return self.text[:5
0] + "..."
󰅂
Template
Inheritance
Template InheritanceMany
elements of a web page are
repeated on every page in
the site, or every page in a
section of the site. By writing
one parent template for the
site, and one for each
section, you can easily
modify the look and feel of
your entire site.
The parent template
The parent template de nes
the elements common to a
set of pages, and de nes
blocks that will be lled by
individual pages
<p>
<a href="{% url 'learn
ing_logs:index' %}">
Learning Log
</a>
</p>
{% block content %}{% e
ndblock content %}
The child template
The child template uses the
{% extends %} template tag
󰅂
Building a page
with data
Most pages in a project
need to present data that’s
speci c to the current user.
URL parameters
A URL often needs to accept a
parameter telling it which
data to access from the
database. The second URL
pattern shown here looks for
the ID of a speci c topic and
stores it in the parameter
topic_id.
urlpatterns = [
url(r'^$', views.inde
x, name='index'),
url(r'^topics/(?P<top
ic_id>d+)/$',
views.topic, name='to
pic'),
]
󰏪
󰅢
to pull in the structure of the
parent template. It then
de nes the content for any
blocks de ned in the parent
template.
{% extends 'learning_lo
gs/base.html' %}
{% block content %}
<p>
Learning Log helps yo
u keep track
of your learning, for
any topic you're
learning about.
</p>
{% endblock content %}
Using data in a view
The view uses a parameter
from the URL to pull the
correct data from the
database. In this example the
view is sending a context
dictionary to the template,
containing data that should
be displayed on the page.
def topic(request, topi
c_id):
"""Show a topic and a
ll its entries."""
topic = Topics.object
s.get(id=topic_id)
entries = topic.entry
_set.order_by('-date_ad
ded')
context = {
'topic': topic,
'entries': entries,
}
return render(reques
t,
'learning_logs/topi
c.html', context)
Using data in a template
The data in the view
function’s context dictionary
is available within the
template. This data is
accessed using template
variables, which are indicated
by doubled curly braces. The
vertical line after a template
variable indicates a lter. In
this case a lter called date
formats date objects, and the
lter linebreaks renders
paragraphs properly on a
web page
{% extends 'learning_lo
gs/base.html' %}
{% block content %}
<p>Topic: {{ topic }}
</p>
<p>Entries:</p>
<ul>
{% for entry in entrie
s %}
<li>
<p>
󰏪
󰅢
CheatSheetMaker.com SimpleCheatSheet.com
{{ entry.date_added|da
te:'M d, Y H:i' }}
</p>
<p>
{{ entry.text|linebrea
ks }}
</p>
</li>
{% empty %}
<li>There are no entri
es yet.</li>
{% endfor %}
</ul>
{% endblock content %}
󰏪
󰅢

More Related Content

What's hot

Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scalarostislav
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Robert DeLuca
 
Utilization of zend an ultimate alternate for intense data processing
Utilization of zend  an ultimate alternate for intense data processingUtilization of zend  an ultimate alternate for intense data processing
Utilization of zend an ultimate alternate for intense data processingCareer at Elsner
 
RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendalltutorialsruby
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptAndrew Lovett-Barron
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular jscodeandyou forums
 
BackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsBackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsJoseph Khan
 
Rails Plugins - Linux For You, March 2011 Issue
Rails Plugins - Linux For You, March 2011 IssueRails Plugins - Linux For You, March 2011 Issue
Rails Plugins - Linux For You, March 2011 IssueSagar Arlekar
 
How to make workout app for watch os 2
How to make workout app for watch os 2How to make workout app for watch os 2
How to make workout app for watch os 2Yusuke Kita
 
Django Templates
Django TemplatesDjango Templates
Django TemplatesWilly Liu
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsScott Gardner
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based ViewsWilly Liu
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web ComponentsMateus Ortiz
 
PyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appenginePyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appenginePranav Prakash
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?DicodingEvent
 

What's hot (19)

Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scala
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
 
Utilization of zend an ultimate alternate for intense data processing
Utilization of zend  an ultimate alternate for intense data processingUtilization of zend  an ultimate alternate for intense data processing
Utilization of zend an ultimate alternate for intense data processing
 
RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendall
 
Angular js
Angular jsAngular js
Angular js
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Intro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate JavascriptIntro to BackboneJS + Intermediate Javascript
Intro to BackboneJS + Intermediate Javascript
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
 
BackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsBackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applications
 
Rails Plugins - Linux For You, March 2011 Issue
Rails Plugins - Linux For You, March 2011 IssueRails Plugins - Linux For You, March 2011 Issue
Rails Plugins - Linux For You, March 2011 Issue
 
How to make workout app for watch os 2
How to make workout app for watch os 2How to make workout app for watch os 2
How to make workout app for watch os 2
 
Django Templates
Django TemplatesDjango Templates
Django Templates
 
Change log
Change logChange log
Change log
 
Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Ch9 .Best Practices for Class-Based Views
Ch9 .Best Practices  for  Class-Based ViewsCh9 .Best Practices  for  Class-Based Views
Ch9 .Best Practices for Class-Based Views
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web Components
 
PyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appenginePyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appengine
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
 

Similar to Django cheat sheet

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Arjan
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگوrailsbootcamp
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web FrameworkDavid Gibbons
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django projectXiaoqi Zhao
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdfjayarao21
 

Similar to Django cheat sheet (20)

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Django crush course
Django crush course Django crush course
Django crush course
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Django
DjangoDjango
Django
 
Django
DjangoDjango
Django
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
 
React django
React djangoReact django
React django
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
Django - basics
Django - basicsDjango - basics
Django - basics
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
 

More from Lam Hoang

Py spark cheat sheet by cheatsheetmaker.com
Py spark cheat sheet by cheatsheetmaker.comPy spark cheat sheet by cheatsheetmaker.com
Py spark cheat sheet by cheatsheetmaker.comLam Hoang
 
VS Code cheat sheet
VS Code cheat sheetVS Code cheat sheet
VS Code cheat sheetLam Hoang
 
PostgreSql cheat sheet
PostgreSql cheat sheetPostgreSql cheat sheet
PostgreSql cheat sheetLam Hoang
 
Nginx cheat sheet
Nginx cheat sheetNginx cheat sheet
Nginx cheat sheetLam Hoang
 
MySql cheat sheet
MySql cheat sheetMySql cheat sheet
MySql cheat sheetLam Hoang
 
Html cheat sheet
Html cheat sheetHtml cheat sheet
Html cheat sheetLam Hoang
 
Git cheat sheet
Git cheat sheetGit cheat sheet
Git cheat sheetLam Hoang
 
Css cheat sheet
Css cheat sheetCss cheat sheet
Css cheat sheetLam Hoang
 
Apache cheat sheet
Apache cheat sheetApache cheat sheet
Apache cheat sheetLam Hoang
 
Battle chatter minecraft 1.4.7 mod
Battle chatter minecraft 1.4.7 modBattle chatter minecraft 1.4.7 mod
Battle chatter minecraft 1.4.7 modLam Hoang
 
On thi dai_hoc_mon_van_2010 (1)
On thi dai_hoc_mon_van_2010 (1)On thi dai_hoc_mon_van_2010 (1)
On thi dai_hoc_mon_van_2010 (1)Lam Hoang
 
ôn thi môn văn
ôn thi môn vănôn thi môn văn
ôn thi môn vănLam Hoang
 
On thi dai_hoc_mon_van_2010
On thi dai_hoc_mon_van_2010On thi dai_hoc_mon_van_2010
On thi dai_hoc_mon_van_2010Lam Hoang
 
giáo trình c căn bản
giáo trình c căn bảngiáo trình c căn bản
giáo trình c căn bảnLam Hoang
 

More from Lam Hoang (14)

Py spark cheat sheet by cheatsheetmaker.com
Py spark cheat sheet by cheatsheetmaker.comPy spark cheat sheet by cheatsheetmaker.com
Py spark cheat sheet by cheatsheetmaker.com
 
VS Code cheat sheet
VS Code cheat sheetVS Code cheat sheet
VS Code cheat sheet
 
PostgreSql cheat sheet
PostgreSql cheat sheetPostgreSql cheat sheet
PostgreSql cheat sheet
 
Nginx cheat sheet
Nginx cheat sheetNginx cheat sheet
Nginx cheat sheet
 
MySql cheat sheet
MySql cheat sheetMySql cheat sheet
MySql cheat sheet
 
Html cheat sheet
Html cheat sheetHtml cheat sheet
Html cheat sheet
 
Git cheat sheet
Git cheat sheetGit cheat sheet
Git cheat sheet
 
Css cheat sheet
Css cheat sheetCss cheat sheet
Css cheat sheet
 
Apache cheat sheet
Apache cheat sheetApache cheat sheet
Apache cheat sheet
 
Battle chatter minecraft 1.4.7 mod
Battle chatter minecraft 1.4.7 modBattle chatter minecraft 1.4.7 mod
Battle chatter minecraft 1.4.7 mod
 
On thi dai_hoc_mon_van_2010 (1)
On thi dai_hoc_mon_van_2010 (1)On thi dai_hoc_mon_van_2010 (1)
On thi dai_hoc_mon_van_2010 (1)
 
ôn thi môn văn
ôn thi môn vănôn thi môn văn
ôn thi môn văn
 
On thi dai_hoc_mon_van_2010
On thi dai_hoc_mon_van_2010On thi dai_hoc_mon_van_2010
On thi dai_hoc_mon_van_2010
 
giáo trình c căn bản
giáo trình c căn bảngiáo trình c căn bản
giáo trình c căn bản
 

Recently uploaded

Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 

Recently uploaded (20)

Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 

Django cheat sheet

  • 1. Django Cheat Sheet Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. by lam 󰅂Starting a Project Create a virtual environment $ virtualenv venv $ source venv/bin/activ ate Install Django $ pip install Django Setup Django Project $ django-admin.py start project projectname Create database $ python manage.py sync db Run Server $ python manage.py runs erver Create App $ python manage.py star tapp appname Add to INATALLED_APPS list Create Templates $ mkdir appname/templat es 󰅂 Working with Model De ning a model To de ne the models for your app, modify the le models.py that was created in your app’s folder. The __str__() method tells Django how to represent data objects based on this model. from django.db import m odels class Topic(models.Mode l): """A topic the user i s learning about.""" text = models.CharFie ld(max_length=200) date_added = models.D ateTimeField( auto_now_add=True) def __str__(self): return self.text Activating a model To use a model the app must be added to the tuple INSTALLED_APPS, which is stored in the project’s settings.py le. INSTALLED_APPS = ( --snip-- 'django.contrib.stati cfiles', # My apps 'learning_logs', ) Migrating the database The database needs to be modi ed to store the kind of 󰅂 Building a simple homepage Users interact with a project through web pages, and a project’s home page can start out as a simple page with no data. A page usually needs a URL, a view, and a template. Mapping a project’s URLs The project’s main urls.py le tells Django where to nd the urls.py les associated with each app in the project from django.conf.urls i mport include, url from django.contrib imp ort admin urlpatterns = [ url(r'^admin/', inclu de(admin.site.urls)), url(r'', include('lea rning_logs.urls', namespace='learning_l ogs')), ] Mapping an app’s URLs An app’s urls.py le tells Django which view to use for each URL in the app. You’ll need to make this le yourself, and save it in the app’s folder. from django.conf.urls i mport url from . import views urlpatterns = [ url(r'^$', views.inde x, name='index'), ] 󰅂Another model A new model can use an existing model. The ForeignKey attribute establishes a connection between instances of the two related models. Make 󰏪 󰅢
  • 2. data that the model represents. $ python manage.py make migrations learning_log s $ python manage.py migr ate Creating a superuser A superuser is a user account that has access to all aspects of the project. $ python manage.py crea tesuperuser Registering a model You can register your models with Django’s admin site, which makes it easier to work with the data in your project. To do this, modify the app’s admin.py le. View the admin site at http://localhost:8000/admin/. from django.contrib imp ort admin from learning_logs.mode ls import Topic admin.site.register(Top ic) Writing a simple view A view takes information from a request and sends data to the browser, often through a template. View functions are stored in an app’s views.py le. This simple view function doesn’t pull in any data, but it uses the template index.html to render the home page from django.shortcuts i mport render def index(request): """The home page for Learning Log.""" return render(reques t, 'learning_logs/inde x.html') Writing a simple template A template sets up the structure for a page. It’s a mix of html and template code, which is like Python but not as powerful. Make a folder called templates inside the project folder. Inside the templates folder make another folder with the same name as the app. This is where the template les should be saved <p>Learning Log</p> <p>Learning Log helps y ou keep track of your learning, for any topi c you're learning about.</p> sure to migrate the database after adding a new model to your app. De ning a model with a foreign key class Entry(models.Mode l): """Learning log entrie s for a topic.""" topic = models.Foreig nKey(Topic) text = models.TextFie ld() date_added = models.D ateTimeField( auto_now_add=True) def __str__(self): return self.text[:5 0] + "..." 󰅂 Template Inheritance Template InheritanceMany elements of a web page are repeated on every page in the site, or every page in a section of the site. By writing one parent template for the site, and one for each section, you can easily modify the look and feel of your entire site. The parent template The parent template de nes the elements common to a set of pages, and de nes blocks that will be lled by individual pages <p> <a href="{% url 'learn ing_logs:index' %}"> Learning Log </a> </p> {% block content %}{% e ndblock content %} The child template The child template uses the {% extends %} template tag 󰅂 Building a page with data Most pages in a project need to present data that’s speci c to the current user. URL parameters A URL often needs to accept a parameter telling it which data to access from the database. The second URL pattern shown here looks for the ID of a speci c topic and stores it in the parameter topic_id. urlpatterns = [ url(r'^$', views.inde x, name='index'), url(r'^topics/(?P<top ic_id>d+)/$', views.topic, name='to pic'), ] 󰏪 󰅢
  • 3. to pull in the structure of the parent template. It then de nes the content for any blocks de ned in the parent template. {% extends 'learning_lo gs/base.html' %} {% block content %} <p> Learning Log helps yo u keep track of your learning, for any topic you're learning about. </p> {% endblock content %} Using data in a view The view uses a parameter from the URL to pull the correct data from the database. In this example the view is sending a context dictionary to the template, containing data that should be displayed on the page. def topic(request, topi c_id): """Show a topic and a ll its entries.""" topic = Topics.object s.get(id=topic_id) entries = topic.entry _set.order_by('-date_ad ded') context = { 'topic': topic, 'entries': entries, } return render(reques t, 'learning_logs/topi c.html', context) Using data in a template The data in the view function’s context dictionary is available within the template. This data is accessed using template variables, which are indicated by doubled curly braces. The vertical line after a template variable indicates a lter. In this case a lter called date formats date objects, and the lter linebreaks renders paragraphs properly on a web page {% extends 'learning_lo gs/base.html' %} {% block content %} <p>Topic: {{ topic }} </p> <p>Entries:</p> <ul> {% for entry in entrie s %} <li> <p> 󰏪 󰅢
  • 4. CheatSheetMaker.com SimpleCheatSheet.com {{ entry.date_added|da te:'M d, Y H:i' }} </p> <p> {{ entry.text|linebrea ks }} </p> </li> {% empty %} <li>There are no entri es yet.</li> {% endfor %} </ul> {% endblock content %} 󰏪 󰅢