SlideShare a Scribd company logo
1 of 32
Introduction to Django
        pyArkansas


        Wade Austin
        @k_wade_a
What is Django?
“Django is a high-level Python Web framework that
encourages rapid development and clean, pragmatic
design.”
                                     www.djangoproject.com


• Created out of the newspaper industry
• Help developers build sites fast
• Encourage Reuse and Lose Coupling
• DRY (don’t repeat yourself)
• Minimal Code
• Opinionated
Batteries Included
             django.contrib


• Admin Interface for editing data.
• Auth module for user accounts
• Syndication module for generation of RSS
• Static Pages
Active Community

• Many Community Contributed Apps
• Pinax
  http://pinaxproject.com/


• Django Packages
  http://djangopackages.com/
Django Projects
•   A project is your website.

•   Projects contain the configuration information for
    your site.

•   Create a project:
    django-admin.py startproject [PROJECT_NAME]

•   Projects contain 3 files:
    •   settings.py - configuration information for your project

    •   urls.py - URL routes defined by your project

    •   manage.py - alias of django-admin.py tuned to your project
Django Applications
• Projects are built from Applications
• Apps encapsulate some piece of
  functionality
  •   blog, photo gallery, shopping cart, etc.

• Apps can be reused
• Apps are Python Packages
• manage.py startapp [MY_APP_NAME]
Django Application
     Components
• Models - Your Data
• Views - Rules for Accessing Data
• Templates - Displays Data
• URL Patterns - Maps URLs to Views
Models

• Describes the data in your apps
• Defined in an app’s models.py file
• Map Python Classes to Database Tables
• Provides an API for creating, retrieving,
  changing and deleting data
Blog Data Definition
CREATE TABLE "blog_category" (
   "id" integer NOT NULL PRIMARY KEY,
   "name" varchar(50) NOT NULL
);

CREATE TABLE "blog_blogpost" (
   "id" integer NOT NULL PRIMARY KEY,
   "title" varchar(100) NOT NULL,
   "slug" varchar(50) NOT NULL UNIQUE,
   "publish_date" datetime NOT NULL,
   "is_published" bool NOT NULL,
   "content" text NOT NULL,
   "category_id" integer NOT NULL REFERENCES "blog_category" ("id")
);
Django Hides the SQL


• SQL is not consistent across databases
• Difficult to store in version control
Model Example
from django.db import models
from datetime import datetime

class Category(models.Model):
    name = models.CharField(max_length=50)

class BlogPost(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    publish_date = models.DateTimeField(default=datetime.now)
    is_published = models.BooleanField(default=False)
    content = models.TextField(blank=True)
    category = models.ForeignKey(Category,
               related_name=‘posts’)
Creating your database

• manage.py syncdb command creates tables
  from models
• Creates all models for any app in your
  project’s INSTALLED_APPS setting
Querying Models
posts = BlogPost.objects.all()

publshed_posts = BlogPost.objects.filter(is_published=True)

news_posts = BlogPost.objects.filter(category__name = 'News')

c = Category(
    name="News"
)
c.save()
Views

• Business Logic
• Perform a task and render output
  (HTML/JSON/XML)


• Python function that takes an HttpRequest
  and returns an HttpResponse
• Defined in an app’s views.py file
Hello World View

from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello World")
Latest Posts View
from django.shortcuts import render
from blog.models import BlogPost

def get_latest_posts(request):
    today = datetime.datetime.now()
    posts = BlogPost.objects.filter(is_published=True).
                    filter(publish_date__lte=today).
                    order_by('-publish_date')

    return render( request, 'blog/latest_posts.html',
                   {'posts':posts})
Post Detail View
from django.shortcuts import render, get_object_or_404
from blog.models import BlogPost

def blog_post_detail(request, slug):
    post = get_object_or_404(BlogPost, slug=slug)
    return render( request, "blog/blogpost_detail.html",
                   {"post":post})
URL Routes

• Defines the URLs used in your project
• Maps a URL to a View Function
• Defined using Regular Expressions
• Defined in an app’s urls.py file.
URL Example

urlpatterns = patterns('',
    url(r'^latest_posts/$',
        'blog.views.get_latest_posts',
        name='blog_blogpost_latest'),

    url(r'^post/(?P<slug>[-w]+)/$',
        'blog.views.blog_post_detail',
        name='blog_blogpost_detail'),
)
Templates
• Describes the Presentation of your data
• Separates Logic from Presentation
• Simple Syntax
• Designer Friendly
• Supports Reuse through inheritance and
  inclusion
• Blocks allow child templates to insert
  content into parent templates
Template Syntax

• Variables: {{variable-name}}
• Tags: Perform logic
  {% include “_form.html” %}
• Filters: Operate on data
  {{post.publish_date|date:"m/d/Y"}}
Template “base.html”
<html>
<head>
    <title>{% block title %}{% endblock %}My Site</title>
    <link rel="stylesheet" href="{{STATIC_URL}}css/screen.css"
                    media="screen, projection"/>
</head>
<body>
    <h1>My test site</h1>

   {% block content %}
   {% endblock %}

</body>
</html>
Template
            “latest_posts.html”
{% extends "base.html" %}

{% block title %}Latest Blog Posts -
{% endblock %}

{% block content %}
    <h2>Latest Blog Posts</h1>
    {% for p in posts %}
        <h3><a href="{% url blog_blogpost_detail p.slug %}">{{p.title}}</a></h3>
        <p><strong>Published:</strong>
          {{p.publish_date|date:"m/d/Y"}}
          </p>
        <div class="content">
            {{p.content|safe}}
        </div>
    {% endfor %}
{% endblock %}


         List of Template Tags and Filters: https://docs.djangoproject.com/en/dev/ref/templates/builtins/
The admin
• Not a CMS
• Allows site admins to edit content
• Auto CRUD views for your models
• Easy to customize
• Optional. If you don’t like it you can write
  your own
Admin List
Admin Edit Screen
The admin

• add django.contrib.admin to
  INSTALLED_APPS
• Uncomment admin import, discover, and url
  pattern from PROJECTS urls.py
• Create an admin.py file for each app you
  want to manage
Sample admin.py

from django.contrib import admin

class BlogPostAdmin(admin.ModelAdmin):
    list_display = ('title', 'publish_date', 'is_published')
    list_filter = ('is_published', 'publish_date')
    search_fields = ('title', 'content')

admin.site.register(BlogPost, BlogPostAdmin)
Other Stuff

• Forms
• Caching
• Testing
Resources
•   Official Django Tutorial
    https://docs.djangoproject.com/en/dev/intro/tutorial01/


•   Django Documentation
    https://docs.djangoproject.com/


•   The Django Book
    http://www.djangobook.com/


• Practical Django Projects
    https://docs.djangoproject.com/


• Pro Django
    http://prodjango.com/
Thank You

    Wade Austin
http://wadeaustin.com
    @k_wade_a

More Related Content

What's hot

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 Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Edureka!
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoKnoldus Inc.
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersRosario Renga
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8rajkumar2011
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkChristopher Foresman
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django frameworkflapiello
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Zhe Li
 
Python web frameworks
Python web frameworksPython web frameworks
Python web frameworksNEWLUG
 

What's hot (20)

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Django
DjangoDjango
Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
django
djangodjango
django
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Basic Python Django
Basic Python DjangoBasic Python Django
Basic Python Django
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Python web frameworks
Python web frameworksPython web frameworks
Python web frameworks
 

Viewers also liked

Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django SiteTeaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django SiteShawn Rider
 
Plone in Higher Education
Plone in Higher EducationPlone in Higher Education
Plone in Higher EducationJazkarta, Inc.
 
Agile Development with Plone
Agile Development with PloneAgile Development with Plone
Agile Development with PloneJazkarta, Inc.
 
Gtd Intro
Gtd IntroGtd Intro
Gtd Introfool2nd
 

Viewers also liked (7)

Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
DjangoCon recap
DjangoCon recapDjangoCon recap
DjangoCon recap
 
Pinax
PinaxPinax
Pinax
 
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django SiteTeaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
 
Plone in Higher Education
Plone in Higher EducationPlone in Higher Education
Plone in Higher Education
 
Agile Development with Plone
Agile Development with PloneAgile Development with Plone
Agile Development with Plone
 
Gtd Intro
Gtd IntroGtd Intro
Gtd Intro
 

Similar to Introduction Django

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
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
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheetLam Hoang
 
Mezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.pyMezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.pyMax Lai
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web FrameworkDavid Gibbons
 
Django Overview
Django OverviewDjango Overview
Django OverviewBrian Tol
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 

Similar to Introduction Django (20)

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to 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
 
Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
 
Tango with django
Tango with djangoTango with django
Tango with django
 
Mezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.pyMezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.py
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
 
Django Overview
Django OverviewDjango Overview
Django Overview
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
Django crush course
Django crush course Django crush course
Django crush course
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
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
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 

Introduction Django

  • 1. Introduction to Django pyArkansas Wade Austin @k_wade_a
  • 2. What is Django? “Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.” www.djangoproject.com • Created out of the newspaper industry • Help developers build sites fast • Encourage Reuse and Lose Coupling • DRY (don’t repeat yourself) • Minimal Code • Opinionated
  • 3. Batteries Included django.contrib • Admin Interface for editing data. • Auth module for user accounts • Syndication module for generation of RSS • Static Pages
  • 4. Active Community • Many Community Contributed Apps • Pinax http://pinaxproject.com/ • Django Packages http://djangopackages.com/
  • 5. Django Projects • A project is your website. • Projects contain the configuration information for your site. • Create a project: django-admin.py startproject [PROJECT_NAME] • Projects contain 3 files: • settings.py - configuration information for your project • urls.py - URL routes defined by your project • manage.py - alias of django-admin.py tuned to your project
  • 6. Django Applications • Projects are built from Applications • Apps encapsulate some piece of functionality • blog, photo gallery, shopping cart, etc. • Apps can be reused • Apps are Python Packages • manage.py startapp [MY_APP_NAME]
  • 7. Django Application Components • Models - Your Data • Views - Rules for Accessing Data • Templates - Displays Data • URL Patterns - Maps URLs to Views
  • 8. Models • Describes the data in your apps • Defined in an app’s models.py file • Map Python Classes to Database Tables • Provides an API for creating, retrieving, changing and deleting data
  • 9. Blog Data Definition CREATE TABLE "blog_category" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(50) NOT NULL ); CREATE TABLE "blog_blogpost" ( "id" integer NOT NULL PRIMARY KEY, "title" varchar(100) NOT NULL, "slug" varchar(50) NOT NULL UNIQUE, "publish_date" datetime NOT NULL, "is_published" bool NOT NULL, "content" text NOT NULL, "category_id" integer NOT NULL REFERENCES "blog_category" ("id") );
  • 10. Django Hides the SQL • SQL is not consistent across databases • Difficult to store in version control
  • 11. Model Example from django.db import models from datetime import datetime class Category(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) publish_date = models.DateTimeField(default=datetime.now) is_published = models.BooleanField(default=False) content = models.TextField(blank=True) category = models.ForeignKey(Category, related_name=‘posts’)
  • 12. Creating your database • manage.py syncdb command creates tables from models • Creates all models for any app in your project’s INSTALLED_APPS setting
  • 13. Querying Models posts = BlogPost.objects.all() publshed_posts = BlogPost.objects.filter(is_published=True) news_posts = BlogPost.objects.filter(category__name = 'News') c = Category( name="News" ) c.save()
  • 14. Views • Business Logic • Perform a task and render output (HTML/JSON/XML) • Python function that takes an HttpRequest and returns an HttpResponse • Defined in an app’s views.py file
  • 15. Hello World View from django.http import HttpResponse def hello_world(request): return HttpResponse("Hello World")
  • 16. Latest Posts View from django.shortcuts import render from blog.models import BlogPost def get_latest_posts(request): today = datetime.datetime.now() posts = BlogPost.objects.filter(is_published=True). filter(publish_date__lte=today). order_by('-publish_date') return render( request, 'blog/latest_posts.html', {'posts':posts})
  • 17. Post Detail View from django.shortcuts import render, get_object_or_404 from blog.models import BlogPost def blog_post_detail(request, slug): post = get_object_or_404(BlogPost, slug=slug) return render( request, "blog/blogpost_detail.html", {"post":post})
  • 18. URL Routes • Defines the URLs used in your project • Maps a URL to a View Function • Defined using Regular Expressions • Defined in an app’s urls.py file.
  • 19. URL Example urlpatterns = patterns('', url(r'^latest_posts/$', 'blog.views.get_latest_posts', name='blog_blogpost_latest'), url(r'^post/(?P<slug>[-w]+)/$', 'blog.views.blog_post_detail', name='blog_blogpost_detail'), )
  • 20. Templates • Describes the Presentation of your data • Separates Logic from Presentation • Simple Syntax • Designer Friendly • Supports Reuse through inheritance and inclusion • Blocks allow child templates to insert content into parent templates
  • 21. Template Syntax • Variables: {{variable-name}} • Tags: Perform logic {% include “_form.html” %} • Filters: Operate on data {{post.publish_date|date:"m/d/Y"}}
  • 22. Template “base.html” <html> <head> <title>{% block title %}{% endblock %}My Site</title> <link rel="stylesheet" href="{{STATIC_URL}}css/screen.css" media="screen, projection"/> </head> <body> <h1>My test site</h1> {% block content %} {% endblock %} </body> </html>
  • 23. Template “latest_posts.html” {% extends "base.html" %} {% block title %}Latest Blog Posts - {% endblock %} {% block content %} <h2>Latest Blog Posts</h1> {% for p in posts %} <h3><a href="{% url blog_blogpost_detail p.slug %}">{{p.title}}</a></h3> <p><strong>Published:</strong> {{p.publish_date|date:"m/d/Y"}} </p> <div class="content"> {{p.content|safe}} </div> {% endfor %} {% endblock %} List of Template Tags and Filters: https://docs.djangoproject.com/en/dev/ref/templates/builtins/
  • 24. The admin • Not a CMS • Allows site admins to edit content • Auto CRUD views for your models • Easy to customize • Optional. If you don’t like it you can write your own
  • 25.
  • 28. The admin • add django.contrib.admin to INSTALLED_APPS • Uncomment admin import, discover, and url pattern from PROJECTS urls.py • Create an admin.py file for each app you want to manage
  • 29. Sample admin.py from django.contrib import admin class BlogPostAdmin(admin.ModelAdmin): list_display = ('title', 'publish_date', 'is_published') list_filter = ('is_published', 'publish_date') search_fields = ('title', 'content') admin.site.register(BlogPost, BlogPostAdmin)
  • 30. Other Stuff • Forms • Caching • Testing
  • 31. Resources • Official Django Tutorial https://docs.djangoproject.com/en/dev/intro/tutorial01/ • Django Documentation https://docs.djangoproject.com/ • The Django Book http://www.djangobook.com/ • Practical Django Projects https://docs.djangoproject.com/ • Pro Django http://prodjango.com/
  • 32. Thank You Wade Austin http://wadeaustin.com @k_wade_a

Editor's Notes

  1. Ask audience questions.\nWho knows Python?\nWho here has used Django?\nExperience building websites / web development?\nOther webdev frameworks?\n
  2. Framework created in 2005 at a newspaper Lawrence Kansas\nCreated out of a need to develop sites fast on a real-world news cycle\nTasked with creating sites at journalism deadline. Be able to launch sites is hours / days as opposed to weeks / months.\nDjango is Python, if you are learning Django you are learning Python.\n\nWhat is a web-framework? It makes routine development tasks easier by using shortcuts.\nExamples: Database CRUD, form processing, clean urls, etc.\nOpinionated about the right way to do things, makes doing things that way easier \nNot a CMS.\n
  3. \n
  4. \n
  5. Projects are your site\n
  6. Projects/Sites tend to have lots of applications\nApps are pieces of re-use.\nApps should be small, sites are made up of lots of apps\n
  7. \n
  8. Describes the types of data your apps have and what fields/attributes those types have\nModels map one-to-one to DB tables\nDB neutral. Hides SQL (unless you need it) SQLite for development, PostGres for production\nsyncdb installs all models listed in INSTALLED_APPS\n\n
  9. \n
  10. \n
  11. Fields for different data types\nCharField short string\nDateTime, Time, Date fields for date/time information\nTextField for larger text information\nBoolean, Integer, Float for example\nForeignKey, ManyToMany, OneToOne for relationships\n\nwell documented online\n
  12. \n
  13. Filters can be chained.\nQuery is not executed until the result is operated so calling filter multi times is not a penalty.\nFields to Query are escaped to prevent against SQL Injection\n
  14. A python function that accepts an HttpRequest and returns a HttpResponse\n
  15. \n
  16. View is a function (or any callable) accepts a HttpRequest object and returns a HttpResponse object\nQuerying BlogPost to get a list of posts that are marked as published and their publish date is not in the future.\nUses a Django shortcut function called render that takes a response, a template name, and dictionary of objects and returns\na response that renders the given template using the dictionary\n\n
  17. \n
  18. \n
  19. 2 URL patters 1 for the latest posts, 1 for post detail\npost detail uses a regex to capture a keyword argument to the view function (slug)\nThe name argument is a unique string to identify a url pattern. Usually named (appname_model_view) to keep from clashes\nUseful so you can reference a URL by its name not hardcode the URL. Decouples the url. allows you to change url and not break stuff\n
  20. Templates can inherit from base template for reuse and include sub templates (i.e. a common form template)\n
  21. \n
  22. Simple HTML layout\nblocks are where inherited templates can generate output\n2 Blocks: title (for page title) &amp; content (for body content)\n
  23. extends the base template\nAdds its base title as just text output\nIterates over each blog posts that was passed in from our view\nPrints out the title, the date formated, and the content|safe\nDjango escapes all HTML output in a template, must mark a field as &amp;#x201C;safe&amp;#x201D; before it is rendered.\n
  24. Admin is not a CMS. Not intended for end uses.\nUseful by site editors/admins to edit data of your models.\nProvides a quick interface for basic site information editing.\nFor many sites it is enough.\nCan be customized.\n
  25. \n
  26. List edit screen. \nsearch at the top, filters on the right\n
  27. \n
  28. \n
  29. Imports Django admin module\nCreates a simple class for the model we want to administer\nSimple things you can do in an admin class. Fields displayed on the list page, fields you can filter by in the admin, fields you can search on.\nMany more customizations listed in docs.\nRegisters that models with the admin class it belongs to\n
  30. \n
  31. \n
  32. \n