SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Django introduction

   Kevin Van Wilder
      www.inuits.eu
Topics
• What is Django?
• Framework overview
• Getting started
Who uses Django?
•   Pinterest           •   New York Times
•   Instagram           •   Washington Post
•   Openstack           •   The Guardian
•   Disqus              •   Mercedes Benz
•   Firefox             •   National Geographic
•   NASA                •   Discovery Channel
•   Bitbucket           •   Orange
•   The Onion           •   ...
What is Django?
• Not a CMS!
• Web application framework to create
  complex, dynamic and datadriven websites
  with emphasis on:
  – Loose coupling and tight cohesion
  – Less code
  – Quick development
  – DRY
  – Consistent
Features
• Admin interface (CRUD)
• Templating
• Form handling
• Internationalisation (i18n)
• Sessions, User management, role-based
  permissions.
• Object-Relational Mapping (ORM)
• Testing Framework
• Fantastic documentation
FRAMEWORK OVERVIEW
Models


 Views


Templates



                   Application
 Models


 Views


Templates
                   Application
                                 Site/Project
                                                Project Structure




      Settings


            Urls


     Templates
Model, View, Template
• Model
  – Abstracts data by defining classes for them and
    stores them in relational tables
• View
  – Takes a browser request and generates what the
    user gets to see
• Template
  – Defines how the user will see the view
Framework
URLConf
• URLs are matched via patterns and mapped
  View functions/classes that create the output.

    urlpatterns = patterns('',
        url(r'^$',
            TipListView.as_view(),
            name='tip-list'),


        url(r'^tips/(?P<slug>[-w]+)/$',
            TipDetailView.as_view(),
            name='tip-detail'),
    )
Views
• Receives a request and generates a response
• Interacts with:
   – Models
   – Templates
   – Caching
• Mostly fits inside one of the following categories:
   –   Show a list of objects
   –   Show details of an object
   –   Create/Update/Delete an object
   –   Show objects by year, month, week, day...
Views (continued)
• Just rendering text:
  – TemplateView
• If that doesn’t float your boat: Mixins
  – SingleObjectMixin
  – FormMixin
  – ModelFormMixin
  – ...
Overview

urlpatterns = patterns('',

    url(r'^books/([w-]+)/$',
        PublisherBookList.as_view(),
        name='author-detail'),

)


class PublisherBookList(ListView):

    template_name = 'books/books_by_publisher.html'

    def get_queryset(self):
        self.publisher = get_object_or_404(Publisher, name=self.args[0])
        return Book.objects.filter(publisher=self.publisher)
Templates
{% extends "base_generic.html" %}

{% block title %}
    {{ publisher.name }}
{% endblock %}

{% block content %}
    <h1>{{ publisher.name }}</h1>
    {% for book in object_list %}
        <h2>
             <a href="{{ book.get_absolute_url }}">
                 {{ book.title }}
             </a>
        </h2>
    {% endfor %}
{% endblock %}
Models
• Abstract representation of data
• Database independent
• Object oriented (methods, inheritance, etc)
from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

   class Meta:
       ordering = ["-name"]

   def __unicode__(self):
       return self.name


class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField('Author')
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
Querying the ORM


Book.objects.get(title=“On the Origin of Species”)



SELECT *
FROM books
WHERE title = “On the Origin of species”;
Querying the ORM
Books.objects

  .filter(genre=“drama”)
  .order_by(“-publish_date”)
  .annotate(author_count=Count(‘author’))
  .only(“title”, “publish_date”, “genre”)
GETTING STARTED
Working on “Onderwijstips”
# SETTING UP ENVIRONMENT
$ mkvirtualenv onderwijstips

#   CHECKING OUT THE CODE
$   git clone git@github.ugent.be:Portaal/site-onderwijstips.git
$   cd site-onderwijstips
$   git checkout develop

#   BUILDING
$   ln –s buildout_dev.cfg buildout.cfg
$   python bootstrap.py
$   bin/buildout –vv # uses private github projects, requires permissions

# STARTING DJANGO
$ bin/django migrate
$ bin/django runserver
Git Repository
• Git Flow (http://nvie.com/posts/a-successful-git-branching-model/)
   – master
       • Always tagged with a version
       • To be deployed
   – develop
       • Next version currently in development
   – release/1.x.x
       • A release being prepared
       • Merges into master with tag 1.x.x
How are we deploying?
• Configuration:
  – Apache2 + mod_wsgi
  – MySQL
  – Optimize only when necessary
    (varnish, memcache, ...)
• Jenkins pipeline
  –   Perform a buildout
  –   Generate .deb file
  –   Upload to Infrastructure Package Repository
  –   Triggers a Puppet run
Onderwijstips
• Three applications
   – Tips (front-end for users)
   – Editors (back-end for tip author)
   – Migration (plomino importer)
• Features:
   –   Haystack search indexing (django-haystack)
   –   User authentication (django-cas)
   –   MediaMosa Integration (django-mediamosa)
   –   Tagging (django-taggit)
   –   Ugent Theming (django-ugent)
• Buildout (Thx Bert!)
• Monitoring via Sentry
• Database schema migration management via South
DEMO TIME!

Contenu connexe

Tendances

jQuery Learning
jQuery LearningjQuery Learning
jQuery Learning
Uzair Ali
 
W3Conf slides - The top web features from caniuse.com you can use today
W3Conf slides - The top web features from caniuse.com you can use todayW3Conf slides - The top web features from caniuse.com you can use today
W3Conf slides - The top web features from caniuse.com you can use today
adeveria
 
Sakai customization talk
Sakai customization talkSakai customization talk
Sakai customization talk
croby
 

Tendances (19)

9 Months Web Development Diploma Course in North Delhi
9 Months Web Development Diploma Course in North Delhi9 Months Web Development Diploma Course in North Delhi
9 Months Web Development Diploma Course in North Delhi
 
6 Months PHP internship in Noida
6 Months PHP internship in Noida6 Months PHP internship in Noida
6 Months PHP internship in Noida
 
bcgr3-jquery
bcgr3-jquerybcgr3-jquery
bcgr3-jquery
 
PhDigital 2020: Web Development
PhDigital 2020: Web DevelopmentPhDigital 2020: Web Development
PhDigital 2020: Web Development
 
Jquery
JqueryJquery
Jquery
 
jQuery Learning
jQuery LearningjQuery Learning
jQuery Learning
 
JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)
 
FFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQueryFFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQuery
 
Introuction To jQuery
Introuction To jQueryIntrouction To jQuery
Introuction To jQuery
 
MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)MongoDB hearts Django? (Django NYC)
MongoDB hearts Django? (Django NYC)
 
W3Conf slides - The top web features from caniuse.com you can use today
W3Conf slides - The top web features from caniuse.com you can use todayW3Conf slides - The top web features from caniuse.com you can use today
W3Conf slides - The top web features from caniuse.com you can use today
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1
 
An introduction to jQuery
An introduction to jQueryAn introduction to jQuery
An introduction to jQuery
 
Sakai customization talk
Sakai customization talkSakai customization talk
Sakai customization talk
 
Hands-on Guide to Object Identification
Hands-on Guide to Object IdentificationHands-on Guide to Object Identification
Hands-on Guide to Object Identification
 
JQuery
JQueryJQuery
JQuery
 
Advanced jQuery (Ajax Exp 2007)
Advanced jQuery (Ajax Exp 2007)Advanced jQuery (Ajax Exp 2007)
Advanced jQuery (Ajax Exp 2007)
 
Why I liked Mezzanine CMS
Why I liked Mezzanine CMSWhy I liked Mezzanine CMS
Why I liked Mezzanine CMS
 
Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)Introduction to jQuery (Ajax Exp 2007)
Introduction to jQuery (Ajax Exp 2007)
 

Similaire à Django introduction @ UGent

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
Yared Ayalew
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
kevinvw
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
Mark Rackley
 
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Lucidworks
 

Similaire à Django introduction @ UGent (20)

Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
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
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
 
SEF2013 - A jQuery Primer for SharePoint
SEF2013 - A jQuery Primer for SharePointSEF2013 - A jQuery Primer for SharePoint
SEF2013 - A jQuery Primer for SharePoint
 
Django Overview
Django OverviewDjango Overview
Django Overview
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Django
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
Challenges of Simple Documents: When Basic isn't so Basic - Cassandra Targett...
 
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Unleashing Creative Freedom with MODX - 2015-08-26 at PHP Zwolle
Unleashing Creative Freedom with MODX - 2015-08-26 at PHP Zwolle Unleashing Creative Freedom with MODX - 2015-08-26 at PHP Zwolle
Unleashing Creative Freedom with MODX - 2015-08-26 at PHP Zwolle
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
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
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

Django introduction @ UGent

  • 1. Django introduction Kevin Van Wilder www.inuits.eu
  • 2. Topics • What is Django? • Framework overview • Getting started
  • 3. Who uses Django? • Pinterest • New York Times • Instagram • Washington Post • Openstack • The Guardian • Disqus • Mercedes Benz • Firefox • National Geographic • NASA • Discovery Channel • Bitbucket • Orange • The Onion • ...
  • 4. What is Django? • Not a CMS! • Web application framework to create complex, dynamic and datadriven websites with emphasis on: – Loose coupling and tight cohesion – Less code – Quick development – DRY – Consistent
  • 5. Features • Admin interface (CRUD) • Templating • Form handling • Internationalisation (i18n) • Sessions, User management, role-based permissions. • Object-Relational Mapping (ORM) • Testing Framework • Fantastic documentation
  • 7. Models Views Templates Application Models Views Templates Application Site/Project Project Structure Settings Urls Templates
  • 8. Model, View, Template • Model – Abstracts data by defining classes for them and stores them in relational tables • View – Takes a browser request and generates what the user gets to see • Template – Defines how the user will see the view
  • 10. URLConf • URLs are matched via patterns and mapped View functions/classes that create the output. urlpatterns = patterns('', url(r'^$', TipListView.as_view(), name='tip-list'), url(r'^tips/(?P<slug>[-w]+)/$', TipDetailView.as_view(), name='tip-detail'), )
  • 11. Views • Receives a request and generates a response • Interacts with: – Models – Templates – Caching • Mostly fits inside one of the following categories: – Show a list of objects – Show details of an object – Create/Update/Delete an object – Show objects by year, month, week, day...
  • 12. Views (continued) • Just rendering text: – TemplateView • If that doesn’t float your boat: Mixins – SingleObjectMixin – FormMixin – ModelFormMixin – ...
  • 13. Overview urlpatterns = patterns('', url(r'^books/([w-]+)/$', PublisherBookList.as_view(), name='author-detail'), ) class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.args[0]) return Book.objects.filter(publisher=self.publisher)
  • 14. Templates {% extends "base_generic.html" %} {% block title %} {{ publisher.name }} {% endblock %} {% block content %} <h1>{{ publisher.name }}</h1> {% for book in object_list %} <h2> <a href="{{ book.get_absolute_url }}"> {{ book.title }} </a> </h2> {% endfor %} {% endblock %}
  • 15. Models • Abstract representation of data • Database independent • Object oriented (methods, inheritance, etc)
  • 16. from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Meta: ordering = ["-name"] def __unicode__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author') publisher = models.ForeignKey(Publisher) publication_date = models.DateField()
  • 17. Querying the ORM Book.objects.get(title=“On the Origin of Species”) SELECT * FROM books WHERE title = “On the Origin of species”;
  • 18. Querying the ORM Books.objects .filter(genre=“drama”) .order_by(“-publish_date”) .annotate(author_count=Count(‘author’)) .only(“title”, “publish_date”, “genre”)
  • 20. Working on “Onderwijstips” # SETTING UP ENVIRONMENT $ mkvirtualenv onderwijstips # CHECKING OUT THE CODE $ git clone git@github.ugent.be:Portaal/site-onderwijstips.git $ cd site-onderwijstips $ git checkout develop # BUILDING $ ln –s buildout_dev.cfg buildout.cfg $ python bootstrap.py $ bin/buildout –vv # uses private github projects, requires permissions # STARTING DJANGO $ bin/django migrate $ bin/django runserver
  • 21. Git Repository • Git Flow (http://nvie.com/posts/a-successful-git-branching-model/) – master • Always tagged with a version • To be deployed – develop • Next version currently in development – release/1.x.x • A release being prepared • Merges into master with tag 1.x.x
  • 22.
  • 23. How are we deploying? • Configuration: – Apache2 + mod_wsgi – MySQL – Optimize only when necessary (varnish, memcache, ...) • Jenkins pipeline – Perform a buildout – Generate .deb file – Upload to Infrastructure Package Repository – Triggers a Puppet run
  • 24. Onderwijstips • Three applications – Tips (front-end for users) – Editors (back-end for tip author) – Migration (plomino importer) • Features: – Haystack search indexing (django-haystack) – User authentication (django-cas) – MediaMosa Integration (django-mediamosa) – Tagging (django-taggit) – Ugent Theming (django-ugent) • Buildout (Thx Bert!) • Monitoring via Sentry • Database schema migration management via South