SlideShare una empresa de Scribd logo
1 de 41
Descargar para leer sin conexión
Django
    Framework web para perfeccionistas com prazos




                         Igor Sobreira
                      www.igorsobreira.com

                                
o que é um framework?




               
“é uma estrutura de suporte definida em que um outro 
     projeto de software pode ser organizado e desenvolvido”

     “Frameworks são projetados com a intenção de facilitar o 
       desenvolvimento de software, habilitando designers e 
     programadores a gastarem mais tempo determinando as 
    exigências do software do que com detalhes de baixo nível 
                           do sistema.”


                                 
o que é django?
        framework web escrito em python
    ●



        desenvolvido no Lowrence Journal­World
    ●



        publicado em julho de 2005
    ●



        open­source (licensa BSD)
    ●




                             
“Django is a high­level Python Web 
    framework that encourages rapid 
    development and clean, pragmatic design”




                        
por que python?




            
altíssimo nível
    ●



        multiparadigma (OO, funcional e procedural)
    ●



        tipagem dinâmica e forte
    ●



        coletor de lixo
    ●



        multiplataforma
    ●



        código limpo
    ●



        fácil de aprender
    ●




                                    
“Produtividade e legibilidade”



                    
onde usar python?
    web
●


    – Django, TurboGears, Pylons. Zope, Plone, Grok...

    desktop
●


    – PyGTK, PyQT, WxPython, TkInter...

    mobile
●


    – PyS60 (Symbian), PyMaemo...


                             
por que usar django?

        feito em Python  :­)
    ●



        MTV == MVC
    ●



        ORM (Mapeamento Objeto Relacional)
    ●



        Interface de Administração automática
    ●



        URLs limpas
    ●



        Boa documentação (+inglês)
    ●



                                
separando as tarefas

    MVC (Model – View – Controller)

    MTV (Model – Template – View)



                       
organizando o código

    um projeto possui uma ou mais aplicações




DRY – Don't Repeat Yourself
                          
caminho de uma requisição




                 
models.py
from datetime import datetime
from django.db import models

class Image(models.Model):
  image = models.ImageField(upload_to='fotos')
  description = models.CharField(max_length=50)
     pub_date = models.DateTimeField(
                     default=datetime.now)

                            
models.py (2)
    BEGIN;
    CREATE TABLE quot;teste_imagequot; (
         quot;idquot; integer NOT NULL PRIMARY KEY,
         quot;imagequot; varchar(100) NOT NULL,
         quot;descriptionquot; varchar(50) NOT NULL,
         quot;pub_datequot; datetime NOT NULL
    );
    COMMIT;

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


class Post(models.Model):
  title = models.CharField(max_length=50)
  content = models.TextField()
  pub_date = models.DateTimeField(default=datetime.now)
  author = models.CharField(max_length=50)
  category = models.ForeignKey(Category)


                                 
models.py (4)
BEGIN;
CREATE TABLE quot;teste_categoryquot; (
   quot;idquot; integer NOT NULL PRIMARY KEY,
   quot;namequot; varchar(50) NOT NULL
);
CREATE TABLE quot;teste_postquot; (
   quot;idquot; integer NOT NULL PRIMARY KEY,
   quot;titlequot; varchar(50) NOT NULL,
   quot;contentquot; text NOT NULL,
   quot;pub_datequot; datetime NOT NULL,
   quot;authorquot; varchar(50) NOT NULL,
   quot;category_idquot; integer NOT NULL REFERENCES
   quot;teste_categoryquot; (quot;idquot;)
);
                              
COMMIT;
persistindo os dados


    cat = Category(name = 'Django')
    cat.save()




                      
persistindo os dados (2)
post = Post( title = 'Primeira app em django',
              content = 'vamos comecar...',
              author = 'Igor',
              category = cat )

post.save()



                          
acessando os dados

     p = Post.objects.all()
    [<Post: Post object>, <Post: Post object>]




                               
acessando os dados (2)


    p = Post.objects.filter(author = 'Igor')




                          
acessando os dados (3)


    p = Post.objects.get(id=2)




                      
urls.py
from django.conf.urls.defaults import *


urlpatters =patterns('myproject.myapp.views',
        (r'^lastest/$', 'last_posts'),
        (r'^post/(d+)/$', 'post_details'),
        (r'^contact/$', 'contact'),
)

                                
views.py
from django.shortcuts import render_to_response
from myapp.models import Post

def last_posts(request):
  posts = Post.objects.order_by('-date')[:5]
  return render_to_response('latest.html',
                            {'posts': posts} )


                         
templates
        hora dos web designers :­)
    ●



        simplesmente arquivos .html com “buracos” que 
    ●


        serão preenchidos com o conteúdo passado pela 
        view




                                 
<html>
<head>
 <title> Blog - {{ post.title }} </title>
</head>
<body>
 <h1> {{ post.title }} </h1>
 <p> {{ post.content }} </p>
 <small> Publicado por {{ post.author }} em
 {{ post.pub_date }} </small>
</body>
</html>
                          
templates  (2)
        variáveis
    ●


             {{ nome }}, {{ lista }}
         –

        filters
    ●


             {{ nome|safe }}
         –

             {{ lista|unordered_list }}
         –

        tags
    ●


             {% for nome in lista %} {{ nome }} {% endfor %}
         –

             {% if condicao %} <b> OK </b> {% endif %}
         –




                                     
templates  (3)


<ul>
    {% for post in last_posts %}
      <li> {{ post|date:quot;d/m/Y h:iquot; }} -
           {{ post.title }} </li>
    {% endfor %}
</ul>


                           
mais facilidades...
     formulários
    ●



     testes
    ●



     controle usuários (auth/auth)
    ●



     internacionalização (i18n)
    ●



     AJAX ?!?!
    ●



     feeds RSS / Atom
    ●



     cache
    ●
                                   
dando uma olhada no admin...



                  
     
     
     
     
dúvidas

      ?

       
http://www.djangoproject.com/
●




        http://www.djangobrasil.org/
●




        http://groups.google.com/group/django­brasil/
●




        http://djangobook.com/
●




        http://www.python.org
●




        http://www.pythonbrasil.com.br/
●




        irc.freenode.net (#django­br, #django)
●


                                        
Igor Sobreira
     www.igorsobreira.com
    ●



     http://djangopeople.net/igorsobreira
    ●



     G­Talk: v2.igor@gmail.com
    ●



     MSN: igor@v2windcenter.com
    ●



     IRC: igors
    ●




                               
se der tempo...



              
formulários
from django import newforms as forms


class ContatoForm(forms.Form):
    nome = forms.CharField(label=u'Nome')
    email = forms.EmailField(label=u'Email',
                                required=False)
    msg = forms.CharField(label=u'Mensagem',
                           widget=forms.Textarea)
                             
Formulários (contato.html)
<form action=quot;.quot; method=quot;postquot;>
{{ form.as_p }}
<input type=quot;submitquot; value=quot;Enviarquot; />
</form>




                         
Formulários (views.py)
def contato(request):
     if request.method == quot;POSTquot;:
       form = ContatoForm(request.POST)
       if form.is_valid():
         # faz algo aqui...
             return HttpResponseRedirect(quot;/sucesso/quot;)
     else:
         form = ContatoForm()
     return render_to_response(quot;contato.htmlquot;,
                               

                                  {quot;formquot;:form})

Más contenido relacionado

La actualidad más candente

CSSプリプロセッサの取扱説明書
CSSプリプロセッサの取扱説明書CSSプリプロセッサの取扱説明書
CSSプリプロセッサの取扱説明書
拓樹 谷
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
danwrong
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
Michelangelo van Dam
 
OpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonOpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con Python
PyCon Italia
 
Html and i_phone_mobile-2
Html and i_phone_mobile-2Html and i_phone_mobile-2
Html and i_phone_mobile-2
tonvanbart
 

La actualidad más candente (20)

Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephp
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 
CSSプリプロセッサの取扱説明書
CSSプリプロセッサの取扱説明書CSSプリプロセッサの取扱説明書
CSSプリプロセッサの取扱説明書
 
Java Script
Java ScriptJava Script
Java Script
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
The Ring programming language version 1.2 book - Part 33 of 84
The Ring programming language version 1.2 book - Part 33 of 84The Ring programming language version 1.2 book - Part 33 of 84
The Ring programming language version 1.2 book - Part 33 of 84
 
[PyConZA 2017] Web Scraping: Unleash your Internet Viking
[PyConZA 2017] Web Scraping: Unleash your Internet Viking[PyConZA 2017] Web Scraping: Unleash your Internet Viking
[PyConZA 2017] Web Scraping: Unleash your Internet Viking
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
 
Inc
IncInc
Inc
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
 
Writing DSLs with Parslet - Wicked Good Ruby Conf
Writing DSLs with Parslet - Wicked Good Ruby ConfWriting DSLs with Parslet - Wicked Good Ruby Conf
Writing DSLs with Parslet - Wicked Good Ruby Conf
 
OpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con PythonOpenERP e l'arte della gestione aziendale con Python
OpenERP e l'arte della gestione aziendale con Python
 
1cst
1cst1cst
1cst
 
CRUD with Dojo
CRUD with DojoCRUD with Dojo
CRUD with Dojo
 
Dollar symbol
Dollar symbolDollar symbol
Dollar symbol
 
Wsomdp
WsomdpWsomdp
Wsomdp
 
Javascript
JavascriptJavascript
Javascript
 
Html and i_phone_mobile-2
Html and i_phone_mobile-2Html and i_phone_mobile-2
Html and i_phone_mobile-2
 

Destacado

molson coors brewing COORS_AR1999
molson coors brewing  COORS_AR1999molson coors brewing  COORS_AR1999
molson coors brewing COORS_AR1999
finance46
 
advance auto parts 2006AnnualReport
advance auto parts 2006AnnualReportadvance auto parts 2006AnnualReport
advance auto parts 2006AnnualReport
finance48
 
molson coors brewing 200710K
molson coors brewing   200710Kmolson coors brewing   200710K
molson coors brewing 200710K
finance46
 
2012 mobile future in focus
2012 mobile future in focus2012 mobile future in focus
2012 mobile future in focus
Mediamaispasque
 
Brannprosjektering 01 generelle krav til sikkerhet ved brann
Brannprosjektering 01 generelle krav til sikkerhet ved brannBrannprosjektering 01 generelle krav til sikkerhet ved brann
Brannprosjektering 01 generelle krav til sikkerhet ved brann
Fred Johansen
 
Crystallized040910
Crystallized040910Crystallized040910
Crystallized040910
klee4vp
 
N.C. State Fair and social media
N.C. State Fair and social mediaN.C. State Fair and social media
N.C. State Fair and social media
guest5e0b61
 
عرض تقديمي1
عرض تقديمي1عرض تقديمي1
عرض تقديمي1
J00D
 

Destacado (20)

molson coors brewing COORS_AR1999
molson coors brewing  COORS_AR1999molson coors brewing  COORS_AR1999
molson coors brewing COORS_AR1999
 
advance auto parts 2006AnnualReport
advance auto parts 2006AnnualReportadvance auto parts 2006AnnualReport
advance auto parts 2006AnnualReport
 
molson coors brewing 200710K
molson coors brewing   200710Kmolson coors brewing   200710K
molson coors brewing 200710K
 
2010 5 25 Pres 27 Mei 10
2010 5 25 Pres 27 Mei 102010 5 25 Pres 27 Mei 10
2010 5 25 Pres 27 Mei 10
 
広島を盛り上げる新しいサービスをつくろう!~レッドハッカソン ひろしま~
広島を盛り上げる新しいサービスをつくろう!~レッドハッカソン ひろしま~広島を盛り上げる新しいサービスをつくろう!~レッドハッカソン ひろしま~
広島を盛り上げる新しいサービスをつくろう!~レッドハッカソン ひろしま~
 
Cybercom Enhanced Security Platform
Cybercom Enhanced Security PlatformCybercom Enhanced Security Platform
Cybercom Enhanced Security Platform
 
Cybercom Enhanced Security Platform, CESP-Access
Cybercom Enhanced Security Platform, CESP-AccessCybercom Enhanced Security Platform, CESP-Access
Cybercom Enhanced Security Platform, CESP-Access
 
Michael
MichaelMichael
Michael
 
2012 mobile future in focus
2012 mobile future in focus2012 mobile future in focus
2012 mobile future in focus
 
Abrona 01112010
Abrona 01112010Abrona 01112010
Abrona 01112010
 
Brannprosjektering 01 generelle krav til sikkerhet ved brann
Brannprosjektering 01 generelle krav til sikkerhet ved brannBrannprosjektering 01 generelle krav til sikkerhet ved brann
Brannprosjektering 01 generelle krav til sikkerhet ved brann
 
clx_q4fy04
clx_q4fy04clx_q4fy04
clx_q4fy04
 
Teaching Online: An Introduction to COI Framework
Teaching Online: An Introduction to COI FrameworkTeaching Online: An Introduction to COI Framework
Teaching Online: An Introduction to COI Framework
 
Crystallized040910
Crystallized040910Crystallized040910
Crystallized040910
 
N.C. State Fair and social media
N.C. State Fair and social mediaN.C. State Fair and social media
N.C. State Fair and social media
 
Clever Advertising
Clever AdvertisingClever Advertising
Clever Advertising
 
Veruprezentace
VeruprezentaceVeruprezentace
Veruprezentace
 
Emixion Koffie verkeerd presentatie - Hoe communiceren met Google
Emixion Koffie verkeerd presentatie - Hoe communiceren met GoogleEmixion Koffie verkeerd presentatie - Hoe communiceren met Google
Emixion Koffie verkeerd presentatie - Hoe communiceren met Google
 
عرض تقديمي1
عرض تقديمي1عرض تقديمي1
عرض تقديمي1
 
The future will be Realtime & Collaborative
The future will be Realtime & CollaborativeThe future will be Realtime & Collaborative
The future will be Realtime & Collaborative
 

Similar a Django - Framework web para perfeccionistas com prazos

Private slideshow
Private slideshowPrivate slideshow
Private slideshow
sblackman
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
Wen-Tien Chang
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
guest5d87aa6
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
Carles Farré
 
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkejElinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Pertti Paavola
 

Similar a Django - Framework web para perfeccionistas com prazos (20)

The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 
Test upload
Test uploadTest upload
Test upload
 
Django
DjangoDjango
Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008Rugalytics | Ruby Manor Nov 2008
Rugalytics | Ruby Manor Nov 2008
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkejElinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Merb jQuery
Merb jQueryMerb jQuery
Merb jQuery
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Último (20)

Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 

Django - Framework web para perfeccionistas com prazos

  • 1. Django Framework web para perfeccionistas com prazos Igor Sobreira www.igorsobreira.com    
  • 3. “é uma estrutura de suporte definida em que um outro  projeto de software pode ser organizado e desenvolvido” “Frameworks são projetados com a intenção de facilitar o  desenvolvimento de software, habilitando designers e  programadores a gastarem mais tempo determinando as  exigências do software do que com detalhes de baixo nível  do sistema.”    
  • 4. o que é django? framework web escrito em python ● desenvolvido no Lowrence Journal­World ● publicado em julho de 2005 ● open­source (licensa BSD) ●    
  • 5. “Django is a high­level Python Web  framework that encourages rapid  development and clean, pragmatic design”    
  • 7. altíssimo nível ● multiparadigma (OO, funcional e procedural) ● tipagem dinâmica e forte ● coletor de lixo ● multiplataforma ● código limpo ● fácil de aprender ●    
  • 9. onde usar python? web ● – Django, TurboGears, Pylons. Zope, Plone, Grok... desktop ● – PyGTK, PyQT, WxPython, TkInter... mobile ● – PyS60 (Symbian), PyMaemo...    
  • 10. por que usar django? feito em Python  :­) ● MTV == MVC ● ORM (Mapeamento Objeto Relacional) ● Interface de Administração automática ● URLs limpas ● Boa documentação (+inglês) ●    
  • 11. separando as tarefas MVC (Model – View – Controller) MTV (Model – Template – View)    
  • 12. organizando o código um projeto possui uma ou mais aplicações DRY – Don't Repeat Yourself    
  • 14. models.py from datetime import datetime from django.db import models class Image(models.Model): image = models.ImageField(upload_to='fotos') description = models.CharField(max_length=50) pub_date = models.DateTimeField( default=datetime.now)    
  • 15. models.py (2) BEGIN; CREATE TABLE quot;teste_imagequot; ( quot;idquot; integer NOT NULL PRIMARY KEY, quot;imagequot; varchar(100) NOT NULL, quot;descriptionquot; varchar(50) NOT NULL, quot;pub_datequot; datetime NOT NULL ); COMMIT;    
  • 16. models.py (3) class Category(models.Model): name = models.CharField(max_length=50) class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() pub_date = models.DateTimeField(default=datetime.now) author = models.CharField(max_length=50) category = models.ForeignKey(Category)    
  • 17. models.py (4) BEGIN; CREATE TABLE quot;teste_categoryquot; ( quot;idquot; integer NOT NULL PRIMARY KEY, quot;namequot; varchar(50) NOT NULL ); CREATE TABLE quot;teste_postquot; ( quot;idquot; integer NOT NULL PRIMARY KEY, quot;titlequot; varchar(50) NOT NULL, quot;contentquot; text NOT NULL, quot;pub_datequot; datetime NOT NULL, quot;authorquot; varchar(50) NOT NULL, quot;category_idquot; integer NOT NULL REFERENCES quot;teste_categoryquot; (quot;idquot;) );     COMMIT;
  • 18. persistindo os dados cat = Category(name = 'Django') cat.save()    
  • 19. persistindo os dados (2) post = Post( title = 'Primeira app em django', content = 'vamos comecar...', author = 'Igor', category = cat ) post.save()    
  • 20. acessando os dados  p = Post.objects.all() [<Post: Post object>, <Post: Post object>]    
  • 21. acessando os dados (2) p = Post.objects.filter(author = 'Igor')    
  • 22. acessando os dados (3) p = Post.objects.get(id=2)    
  • 23. urls.py from django.conf.urls.defaults import * urlpatters =patterns('myproject.myapp.views', (r'^lastest/$', 'last_posts'), (r'^post/(d+)/$', 'post_details'), (r'^contact/$', 'contact'), )    
  • 24. views.py from django.shortcuts import render_to_response from myapp.models import Post def last_posts(request): posts = Post.objects.order_by('-date')[:5] return render_to_response('latest.html', {'posts': posts} )    
  • 25. templates hora dos web designers :­) ● simplesmente arquivos .html com “buracos” que  ● serão preenchidos com o conteúdo passado pela  view    
  • 26. <html> <head> <title> Blog - {{ post.title }} </title> </head> <body> <h1> {{ post.title }} </h1> <p> {{ post.content }} </p> <small> Publicado por {{ post.author }} em {{ post.pub_date }} </small> </body> </html>    
  • 27. templates  (2) variáveis ● {{ nome }}, {{ lista }} – filters ● {{ nome|safe }} – {{ lista|unordered_list }} – tags ● {% for nome in lista %} {{ nome }} {% endfor %} – {% if condicao %} <b> OK </b> {% endif %} –    
  • 28. templates  (3) <ul> {% for post in last_posts %} <li> {{ post|date:quot;d/m/Y h:iquot; }} - {{ post.title }} </li> {% endfor %} </ul>    
  • 29. mais facilidades...  formulários ●  testes ●  controle usuários (auth/auth) ●  internacionalização (i18n) ●  AJAX ?!?! ●  feeds RSS / Atom ●  cache ●    
  • 31.    
  • 32.    
  • 33.    
  • 34.    
  • 35. dúvidas ?    
  • 36. http://www.djangoproject.com/ ● http://www.djangobrasil.org/ ● http://groups.google.com/group/django­brasil/ ● http://djangobook.com/ ● http://www.python.org ● http://www.pythonbrasil.com.br/ ● irc.freenode.net (#django­br, #django) ●    
  • 37. Igor Sobreira  www.igorsobreira.com ●  http://djangopeople.net/igorsobreira ●  G­Talk: v2.igor@gmail.com ●  MSN: igor@v2windcenter.com ●  IRC: igors ●    
  • 39. formulários from django import newforms as forms class ContatoForm(forms.Form): nome = forms.CharField(label=u'Nome') email = forms.EmailField(label=u'Email', required=False) msg = forms.CharField(label=u'Mensagem', widget=forms.Textarea)    
  • 40. Formulários (contato.html) <form action=quot;.quot; method=quot;postquot;> {{ form.as_p }} <input type=quot;submitquot; value=quot;Enviarquot; /> </form>    
  • 41. Formulários (views.py) def contato(request): if request.method == quot;POSTquot;: form = ContatoForm(request.POST) if form.is_valid(): # faz algo aqui... return HttpResponseRedirect(quot;/sucesso/quot;) else: form = ContatoForm() return render_to_response(quot;contato.htmlquot;,     {quot;formquot;:form})