SlideShare a Scribd company logo
Django
Quickstart
Works for
    That’s me




https://www.facebook.com/groups/
What is Django?
Demo: http://
Setting-up development
      environment

 ‣ virtualenv + virtualenvwrapper
Installing virtualenv and
      virtualenvwrapper
   $ pip install virtualenv

        then edit your .profile on osx or .bashrc
         on linux and add the following lines:


export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh

          reload your .profile or .bashrc files:


                $ . ~/.profile
Creating your virtual
            environment
             $ mkvirtualenv pyconph


              activating a virtual environment:

                  $ workon pyconph


                 for windows users:
‣ https://github.com/davidmarble/virtualenvwrapper-win
‣ https://bitbucket.org/guillermooo/virtualenvwrapper-
Installing Django

  $ pip install Django


 testing your Django installation:


$ python
>>> import django
>>> django.VERSION
(1, 4, 0, 'final', 0)
Creating a Django project
$ django-admin.py startproject quickstart


       Starting Django’s development server:



$ cd quickstart
$ python manage.py runserver
...
Development server is running at http://
127.0.0.1:8000/
Quit the server with CONTROL-C.
http://localhost:8000
Configuring your
 Django project
Django project directory structure:


 quickstart
 ├── manage.py
 └── quickstart
     ├── __init__.py
     ├── settings.py
     ├── urls.py
     └── wsgi.py
Setting-up database


quickstart/settings.py

 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
         'NAME': 'quickstart.sqlite',
         'USER': '',
         'PASSWORD': '',
         'HOST': '',
         'PORT': '',
     }
 }
Setting-up directories

quickstart/settings.py
 import os

 PROJECT_ROOT = os.path.split(os.path.abspath(
     os.path.dirname(__file__)))[0]

 STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
 STATIC_URL = '/static/'

 STATICFILES_DIRS = (
     os.path.join(PROJECT_ROOT, 'assets'),
 )
 ...
 TEMPLATE_DIRS = (
     os.path.join(PROJECT_ROOT, 'templates'),
 )
Creating directories

$ mkdir assets static templates



    quickstart
    ├── assets
    ├── manage.py
    ├── quickstart
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   ├── wsgi.py
    ├── static
    └── templates
Creating local settings

$ vim quickstart/localsettings.py

 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
         'NAME': 'quickstart.sqlite',
         'USER': '',
         'PASSWORD': '',
         'HOST': '',
         'PORT': '',
     }
 }
Creating local settings

quickstart/settings.py
 DATABASES = {
      'default': {
           'ENGINE': 'django.db.backends.',
           'NAME': '',
           'USER': '',
           'PASSWORD': '',
           'HOST': '',
           'PORT': '',
      }
 }
 ...
 try:
      from localsettings import *
 except ImportError:
      pass
Syncing the database

$ python manage.py syncdb
Creating tables ...
...
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'marconi'):
E-mail address: wombat@gmail.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Enabling the Django Admin

quickstart/settings.py

 INSTALLED_APPS = (
     ...
     'django.contrib.admin',
 )
Enabling the Django Admin

quickstart/urls.py
 from django.conf.urls import patterns, include, url

 from django.contrib import admin
 admin.autodiscover()

 urlpatterns = patterns('',
     url(r'^admin/', include(admin.site.urls)),
 )
Enabling the Django Admin
    $ python manage.py syncdb


    visit http://127.0.0.1/
Creating a Django App
$ django-admin.py startapp todo


     default app structure:

      todo
      ├── __init__.py
      ├── models.py
      ├── tests.py
      └── views.py
Installing your app



quickstart/settings.py
 INSTALLED_APPS = (
     ...
     'todo',
 )
Creating models


todo/models.py
 1 from django.db import models
 2
 3 class Todo(models.Model):
 4 name = models.CharField(max_length=100)
 5 is_done = models.BooleanField(default=False)
 6 created =
 models.DateTimeField(auto_now_add=True)
 8




                     Syncing
      $ python manage.py syncdb
Exposing models to Django



$ vim todo/admin.py

 from django.contrib import admin
 from todo.models import Todo

 class TodoAdmin(admin.ModelAdmin):
     pass

 admin.site.register(Todo, TodoAdmin)
Exposing models to Django
Creating forms
$ vim todo/forms.py

 1    from django import forms
 2    from todo.models import Todo
 3
 4    class TodoForm(forms.ModelForm):
 5        class Meta:
 6            model = Todo
 7            fields = ('name',)
 8
 9    class TodoListForm(forms.Form):
 10       def __init__(self, *args, **kwargs):
 11           todos = kwargs.pop('todos', [])
 12           super(TodoListForm, self).__init__(*args, **kwargs)
 13           for todo in todos:
 14               field = str(todo.id)
 15               self.fields[field] = forms.BooleanField(
 16                   required=False, label=todo.name)
 17               self.fields[field].is_done = todo.is_done
 18
 19       def clean(self):
 20           selected = [tid for tid, val in self.cleaned_data.items() if val]
 21           if not selected:
 22               raise forms.ValidationError("You need to select one or more items.")
 23           return selected
Creating views

todo/views.py

 1   from django.shortcuts import render_to_response, redirect
 2   from django.template import RequestContext
 3   from django.contrib import messages
 4
 5   from todo.forms import TodoListForm, TodoForm
 6   from todo.models import Todo

 ...
todo/views.py
 9 def home(request):
 10    todos = Todo.objects.order_by('-created')
 11    if request.method == 'POST':
 12        action = request.POST['action'].lower()
 13        todo_list_form = TodoListForm(data=request.POST, todos=todos)
 14        if todo_list_form.is_valid():
 15            selected = Todo.objects.filter(
 16                id__in=todo_list_form.cleaned_data)
 17            actions = {'done': lambda items: items.update(is_done=True),
 18                       'delete': lambda items: items.delete()}
 19            actions.get(action)(selected)
 20            messages.add_message(request, messages.SUCCESS,
 21                                  'Items has been updated.')
 22        else:
 23            messages.add_message(request, messages.ERROR,
 24                                  ''.join(todo_list_form.non_field_errors()))
 25        return redirect('home')
 26    else:
 27        todo_form = TodoForm()
 28        todo_list_form = TodoListForm(todos=todos)
 29    context = {'todo_list_form': todo_list_form, 'todo_form': todo_form}
 30    return render_to_response('todo/home.html', context,
 31                               RequestContext(request))
Creating views

todo/views.py
 34 def new_todo(request):
 35     if not request.method == 'POST':
 36         return redirect('home')
 37     todo_form = TodoForm(request.POST)
 38     if todo_form.is_valid():
 39         todo_form.save()
 40         messages.add_message(request, messages.SUCCESS,
 41                              'Item has been added.')
 42     else:
 43         messages.add_message(request, messages.ERROR,
 44                              'You need to enter a name.')
 45     return redirect('home')
Creating templates



$ mkdir templates/todo
$ touch templates/base.html
$ touch templates/todo/home.html
templates/base.html
 1    <html>
 2    <head>
 3       <title>TODO</title>
 4       <style type="text/css">
 5            fieldset {
 6                  width: 300px;
 7            }
 8       </style>
 9    </head>
 10   <body>
 11   {% if messages %}
 12   <section id="messages">
 13       <ul>
 14             {% for message in messages %}
 15                 <li>
 16                      {{ message }}
 17                 </li>
 18             {% endfor %}
 19       </ul>
 20   </section>
 21   {% endif %}
 22   {% block content %}
 23   {% endblock content %}
 24   </body>
 25   </html>
templates/todo/
1     {% extends "base.html" %}
2
3     {% block content %}
4     <form method="POST" action="{% url new_todo %}">
5        {% csrf_token %}
6        <fieldset>
7             <legend>Add new todo</legend>
8             <div class="field">
9                 {{ todo_form.name.label_tag }}
10                {{ todo_form.name }}
11                {% if todo_form.name.errors %}
12                    {{ todo_form.name.errors }}
13                {% endif %}
14            </div>
15            <input type="submit" name="action" value="Add">
16       </fieldset>
17    </form>

...
templates/todo/
...

19 <form method="POST">
20     {% csrf_token %}
21     <fieldset>
22         <legend>Items todo</legend>
23         {% for field in todo_list_form %}
24             <div class="field">
25                 {{ field }}
26                 <label for="{{ field.auto_id }}"
27                      {% if field.field.is_done %}
28                          style="text-decoration:line-through;"
29                      {% endif %}>
30                      {{ field.label }}
31                 </label>
32             </div>
33         {% empty %}
34             <p>You don't have anymore items todo.</p>
35         {% endfor %}
36     </fieldset>
37     <br />
38     <input type="submit" name="action" value="Done">
39     <input type="submit" name="action" value="Delete">
40 </form>
41 {% endblock content %}
Adding urls:
quickstart/urls.py

 urlpatterns = patterns('',
     ...
     url(r'^$', 'todo.views.home', name='home'),
     url(r'^todo/', include('todo.urls')),
 )



$ vim todo/urls.py

 from django.conf.urls import patterns, url

 urlpatterns = patterns('todo.views',
     url(r'^new/$', 'new_todo', name='new_todo'),
 )
Our TODO site:
Thank you :)

More Related Content

What's hot

How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
Luc Bors
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
eugenio pombi
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
Hugo Hamon
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
Aleix Vergés
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
NSCoder Mexico
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In RailsLouie Zhao
 
Why ruby
Why rubyWhy ruby
Why ruby
rstankov
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Backbone js
Backbone jsBackbone js
Backbone js
rstankov
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
rstankov
 
R57shell
R57shellR57shell
R57shell
ady36
 
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8
Wilson Su
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
Rebecca Murphey
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
Samuel ROZE
 
The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
Mahmoud Samir Fayed
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
Samuel ROZE
 

What's hot (20)

How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In Rails
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
R57shell
R57shellR57shell
R57shell
 
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
 
The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 

Viewers also liked

We Buy Cheese in a Cheese Shop
We Buy Cheese in a Cheese ShopWe Buy Cheese in a Cheese Shop
We Buy Cheese in a Cheese Shop
Tzu-ping Chung
 
Python, Development Environment for Windows
Python, Development Environment for WindowsPython, Development Environment for Windows
Python, Development Environment for Windows
Kwangyoun Jung
 
Python Recipes for django girls seoul
Python Recipes for django girls seoulPython Recipes for django girls seoul
Python Recipes for django girls seoul
Joeun Park
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia ContiniWEBdeBS
 
2 × 3 = 6
2 × 3 = 62 × 3 = 6
2 × 3 = 6
Tzu-ping Chung
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
Tzu-ping Chung
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论
Na Lee
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
Tzu-ping Chung
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
WEBdeBS
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.py
Tzu-ping Chung
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
Clayton Parker
 
Website optimization
Website optimizationWebsite optimization
Website optimization
Mindfire Solutions
 
Overview of Testing Talks at Pycon
Overview of Testing Talks at PyconOverview of Testing Talks at Pycon
Overview of Testing Talks at Pycon
Jacqueline Kazil
 
2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python
Jiho Lee
 
User-centered open source
User-centered open sourceUser-centered open source
User-centered open source
Jacqueline Kazil
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘
Jiho Lee
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
Markus Zapke-Gründemann
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_WEBdeBS
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVC
Mindfire Solutions
 
Load testing
Load testingLoad testing
Load testing
Mindfire Solutions
 

Viewers also liked (20)

We Buy Cheese in a Cheese Shop
We Buy Cheese in a Cheese ShopWe Buy Cheese in a Cheese Shop
We Buy Cheese in a Cheese Shop
 
Python, Development Environment for Windows
Python, Development Environment for WindowsPython, Development Environment for Windows
Python, Development Environment for Windows
 
Python Recipes for django girls seoul
Python Recipes for django girls seoulPython Recipes for django girls seoul
Python Recipes for django girls seoul
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia Contini
 
2 × 3 = 6
2 × 3 = 62 × 3 = 6
2 × 3 = 6
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.py
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
 
Website optimization
Website optimizationWebsite optimization
Website optimization
 
Overview of Testing Talks at Pycon
Overview of Testing Talks at PyconOverview of Testing Talks at Pycon
Overview of Testing Talks at Pycon
 
2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python
 
User-centered open source
User-centered open sourceUser-centered open source
User-centered open source
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVC
 
Load testing
Load testingLoad testing
Load testing
 

Similar to Django quickstart

Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Django crush course
Django crush course Django crush course
Django crush course
Mohammed El Rafie Tarabay
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
Python Ireland
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentationScott Messinger
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
Lars Jankowfsky
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
Allie Jones
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Django
DjangoDjango
Django
Ivan Widodo
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
MoscowDjango
 
Awesome State Management for React and Other Virtual-Dom Libraries
Awesome State Management for React and Other Virtual-Dom LibrariesAwesome State Management for React and Other Virtual-Dom Libraries
Awesome State Management for React and Other Virtual-Dom Libraries
FITC
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Zagreb workshop
Zagreb workshopZagreb workshop
Zagreb workshopLynn Root
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
ananelson
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppSyed Shahul
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
Sérgio Santos
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 

Similar to Django quickstart (20)

Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Django crush course
Django crush course Django crush course
Django crush course
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentation
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django
DjangoDjango
Django
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Awesome State Management for React and Other Virtual-Dom Libraries
Awesome State Management for React and Other Virtual-Dom LibrariesAwesome State Management for React and Other Virtual-Dom Libraries
Awesome State Management for React and Other Virtual-Dom Libraries
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Zagreb workshop
Zagreb workshopZagreb workshop
Zagreb workshop
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 

Django quickstart

  • 2. Works for That’s me https://www.facebook.com/groups/
  • 4.
  • 6. Setting-up development environment ‣ virtualenv + virtualenvwrapper
  • 7. Installing virtualenv and virtualenvwrapper $ pip install virtualenv then edit your .profile on osx or .bashrc on linux and add the following lines: export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh reload your .profile or .bashrc files: $ . ~/.profile
  • 8. Creating your virtual environment $ mkvirtualenv pyconph activating a virtual environment: $ workon pyconph for windows users: ‣ https://github.com/davidmarble/virtualenvwrapper-win ‣ https://bitbucket.org/guillermooo/virtualenvwrapper-
  • 9. Installing Django $ pip install Django testing your Django installation: $ python >>> import django >>> django.VERSION (1, 4, 0, 'final', 0)
  • 10. Creating a Django project $ django-admin.py startproject quickstart Starting Django’s development server: $ cd quickstart $ python manage.py runserver ... Development server is running at http:// 127.0.0.1:8000/ Quit the server with CONTROL-C.
  • 12. Configuring your Django project Django project directory structure: quickstart ├── manage.py └── quickstart ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
  • 13. Setting-up database quickstart/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'quickstart.sqlite', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }
  • 14. Setting-up directories quickstart/settings.py import os PROJECT_ROOT = os.path.split(os.path.abspath( os.path.dirname(__file__)))[0] STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'assets'), ) ... TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates'), )
  • 15. Creating directories $ mkdir assets static templates quickstart ├── assets ├── manage.py ├── quickstart │   ├── __init__.py │   ├── settings.py │   ├── urls.py │   ├── wsgi.py ├── static └── templates
  • 16. Creating local settings $ vim quickstart/localsettings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'quickstart.sqlite', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }
  • 17. Creating local settings quickstart/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } ... try: from localsettings import * except ImportError: pass
  • 18. Syncing the database $ python manage.py syncdb Creating tables ... ... Would you like to create one now? (yes/no): yes Username (leave blank to use 'marconi'): E-mail address: wombat@gmail.com Password: Password (again): Superuser created successfully. Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s)
  • 19. Enabling the Django Admin quickstart/settings.py INSTALLED_APPS = ( ... 'django.contrib.admin', )
  • 20. Enabling the Django Admin quickstart/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), )
  • 21. Enabling the Django Admin $ python manage.py syncdb visit http://127.0.0.1/
  • 22. Creating a Django App $ django-admin.py startapp todo default app structure: todo ├── __init__.py ├── models.py ├── tests.py └── views.py
  • 23. Installing your app quickstart/settings.py INSTALLED_APPS = ( ... 'todo', )
  • 24. Creating models todo/models.py 1 from django.db import models 2 3 class Todo(models.Model): 4 name = models.CharField(max_length=100) 5 is_done = models.BooleanField(default=False) 6 created = models.DateTimeField(auto_now_add=True) 8 Syncing $ python manage.py syncdb
  • 25. Exposing models to Django $ vim todo/admin.py from django.contrib import admin from todo.models import Todo class TodoAdmin(admin.ModelAdmin): pass admin.site.register(Todo, TodoAdmin)
  • 27. Creating forms $ vim todo/forms.py 1 from django import forms 2 from todo.models import Todo 3 4 class TodoForm(forms.ModelForm): 5 class Meta: 6 model = Todo 7 fields = ('name',) 8 9 class TodoListForm(forms.Form): 10 def __init__(self, *args, **kwargs): 11 todos = kwargs.pop('todos', []) 12 super(TodoListForm, self).__init__(*args, **kwargs) 13 for todo in todos: 14 field = str(todo.id) 15 self.fields[field] = forms.BooleanField( 16 required=False, label=todo.name) 17 self.fields[field].is_done = todo.is_done 18 19 def clean(self): 20 selected = [tid for tid, val in self.cleaned_data.items() if val] 21 if not selected: 22 raise forms.ValidationError("You need to select one or more items.") 23 return selected
  • 28. Creating views todo/views.py 1 from django.shortcuts import render_to_response, redirect 2 from django.template import RequestContext 3 from django.contrib import messages 4 5 from todo.forms import TodoListForm, TodoForm 6 from todo.models import Todo ...
  • 29. todo/views.py 9 def home(request): 10 todos = Todo.objects.order_by('-created') 11 if request.method == 'POST': 12 action = request.POST['action'].lower() 13 todo_list_form = TodoListForm(data=request.POST, todos=todos) 14 if todo_list_form.is_valid(): 15 selected = Todo.objects.filter( 16 id__in=todo_list_form.cleaned_data) 17 actions = {'done': lambda items: items.update(is_done=True), 18 'delete': lambda items: items.delete()} 19 actions.get(action)(selected) 20 messages.add_message(request, messages.SUCCESS, 21 'Items has been updated.') 22 else: 23 messages.add_message(request, messages.ERROR, 24 ''.join(todo_list_form.non_field_errors())) 25 return redirect('home') 26 else: 27 todo_form = TodoForm() 28 todo_list_form = TodoListForm(todos=todos) 29 context = {'todo_list_form': todo_list_form, 'todo_form': todo_form} 30 return render_to_response('todo/home.html', context, 31 RequestContext(request))
  • 30. Creating views todo/views.py 34 def new_todo(request): 35 if not request.method == 'POST': 36 return redirect('home') 37 todo_form = TodoForm(request.POST) 38 if todo_form.is_valid(): 39 todo_form.save() 40 messages.add_message(request, messages.SUCCESS, 41 'Item has been added.') 42 else: 43 messages.add_message(request, messages.ERROR, 44 'You need to enter a name.') 45 return redirect('home')
  • 31. Creating templates $ mkdir templates/todo $ touch templates/base.html $ touch templates/todo/home.html
  • 32. templates/base.html 1 <html> 2 <head> 3 <title>TODO</title> 4 <style type="text/css"> 5 fieldset { 6 width: 300px; 7 } 8 </style> 9 </head> 10 <body> 11 {% if messages %} 12 <section id="messages"> 13 <ul> 14 {% for message in messages %} 15 <li> 16 {{ message }} 17 </li> 18 {% endfor %} 19 </ul> 20 </section> 21 {% endif %} 22 {% block content %} 23 {% endblock content %} 24 </body> 25 </html>
  • 33. templates/todo/ 1 {% extends "base.html" %} 2 3 {% block content %} 4 <form method="POST" action="{% url new_todo %}"> 5 {% csrf_token %} 6 <fieldset> 7 <legend>Add new todo</legend> 8 <div class="field"> 9 {{ todo_form.name.label_tag }} 10 {{ todo_form.name }} 11 {% if todo_form.name.errors %} 12 {{ todo_form.name.errors }} 13 {% endif %} 14 </div> 15 <input type="submit" name="action" value="Add"> 16 </fieldset> 17 </form> ...
  • 34. templates/todo/ ... 19 <form method="POST"> 20 {% csrf_token %} 21 <fieldset> 22 <legend>Items todo</legend> 23 {% for field in todo_list_form %} 24 <div class="field"> 25 {{ field }} 26 <label for="{{ field.auto_id }}" 27 {% if field.field.is_done %} 28 style="text-decoration:line-through;" 29 {% endif %}> 30 {{ field.label }} 31 </label> 32 </div> 33 {% empty %} 34 <p>You don't have anymore items todo.</p> 35 {% endfor %} 36 </fieldset> 37 <br /> 38 <input type="submit" name="action" value="Done"> 39 <input type="submit" name="action" value="Delete"> 40 </form> 41 {% endblock content %}
  • 35. Adding urls: quickstart/urls.py urlpatterns = patterns('', ... url(r'^$', 'todo.views.home', name='home'), url(r'^todo/', include('todo.urls')), ) $ vim todo/urls.py from django.conf.urls import patterns, url urlpatterns = patterns('todo.views', url(r'^new/$', 'new_todo', name='new_todo'), )

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n