SlideShare una empresa de Scribd logo
1 de 64
Descargar para leer sin conexión
Farkas Szilveszter
Magyarországi Web Konferencia
Budapest, 2009. október 3.
Farkas Szilveszter
Farkas Szilveszter
Farkas Szilveszter
Farkas Szilveszter
from presentation import (Django,
                          Forms,
                          Middleware,
                          Tests,
                          Python)
>>> import django

>>> django.ORIGINAL_AUTHOR
'Adrian Holovaty'

>>> django.OPEN_SOURCED
datetime.date(2005, 7, 13)

>>> django.VERSION
'1.1-final'

>>> len(django.AUTHORS)
485
>>> import django

>>> django.ORIGINAL_AUTHOR
'Adrian Holovaty'

>>> django.OPEN_SOURCED
datetime.date(2005, 7, 13)

>>> django.VERSION
'1.1-final'

>>> len(django.AUTHORS)
485
>>> import django

>>> django.ORIGINAL_AUTHOR
'Adrian Holovaty'

>>> django.OPEN_SOURCED
datetime.date(2005, 7, 13)

>>> django.VERSION
'1.1-final'

>>> len(django.AUTHORS)
485
>>> import django

>>> django.ORIGINAL_AUTHOR
'Adrian Holovaty'

>>> django.OPEN_SOURCED
datetime.date(2005, 7, 13)

>>> django.VERSION
'1.1-final'

>>> len(django.AUTHORS)
485
>>> import django

>>> django.ORIGINAL_AUTHOR
'Adrian Holovaty'

>>> django.OPEN_SOURCED
datetime.date(2005, 7, 13)

>>> django.VERSION
'1.1-final'

>>> len(django.AUTHORS)
485
>>> django.MODEL
'model'

>>> django.VIEW
'template'

>>> django.CONTROLLER
'view'
$ django-admin startproject webkonf

$ cd webkonf

$ ./manage.py startapp conference
from django.db import models

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

class Conference(models.Model):
    name = models.CharField(max_length=32)
    venue = models.ForeignKey(ConferenceVenue)

from django.contrib.auth.models import User

class Attendee(models.Model):
    user = models.OneToOneField(User)
    conferences = models.ManyToManyField(
        Conference, related_name='attendees')
from django.db import models

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

class Conference(models.Model):
    name = models.CharField(max_length=32)
    venue = models.ForeignKey(Venue)

from django.contrib.auth.models import User

class Attendee(models.Model):
    user = models.OneToOneField(User)
    conferences = models.ManyToManyField(
        Conference, related_name='attendees')
from django.db import models

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

class Conference(models.Model):
    name = models.CharField(max_length=32)
    venue = models.ForeignKey(Venue)

from django.contrib.auth.models import User

class Attendee(models.Model):
    user = models.OneToOneField(User)
    conferences = models.ManyToManyField(
        Conference, related_name='attendees')
[...]
<h1>{{ conference.name }}</h1>

<h2>Látogatók</h2>

<ul>
{% for attendee in conference.attendees.all %}
  <li>{{ attendee.user.get_full_name }}</li>
{% endfor %}
</ul>
[...]
from django.shortcuts import (get_object_or_404,
                              render_to_response)
from conference.models import Conference

def conference_page(request, conf_id):
    conference = get_object_or_404(
        Conference, pk=conf_id)
    context = {
        'conference': conference
    }
    return render_to_response(
        'conference.html', context)
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^/conf/(?P<conf_id>d+)/$',
     'conference.views.conference_page'),
)
from django import forms
űrlapok
űrlapok


szerver oldali adatellenőrzés
Űrlap osztály

class AttendeeForm(forms.Form):

Mező

name = forms.CharField('Név', max_length=32)

Widget

password = forms.CharField(
    'Jelszó',
    max_length=32,
    widget=forms.PasswordInput())
Űrlap osztály

class AttendeeForm(forms.Form):

Mező

name = forms.CharField('Név', max_length=32)

Widget

password = forms.CharField(
    'Jelszó',
    max_length=32,
    widget=forms.PasswordInput())
Űrlap osztály

class AttendeeForm(forms.Form):

Mező

name = forms.CharField('Név', max_length=32)

Widget

password = forms.CharField(
    'Jelszó',
    max_length=32,
    widget=forms.PasswordInput())
Beépített ellenőrzés

email = forms.EmailField(max_length=75)
zip = forms.IntegerField(min_value=1000,
                         max_value=9999)

Mezőszintű egyedi ellenőrzés

def clean_FIELDNAME(self):

Űrlapszintű egyedi ellenőrzés

def clean(self):
Beépített ellenőrzés

email = forms.EmailField(max_length=75)
zip = forms.IntegerField(min_value=1000,
                         max_value=9999)

Mezőszintű egyedi ellenőrzés

def clean_FIELDNAME(self):

Űrlapszintű egyedi ellenőrzés

def clean(self):
Beépített ellenőrzés

email = forms.EmailField(max_length=75)
zip = forms.IntegerField(min_value=1000,
                         max_value=9999)

Mezőszintű egyedi ellenőrzés

def clean_FIELDNAME(self):

Űrlapszintű egyedi ellenőrzés

def clean(self):
Mezőszintű egyedi ellenőrzés

def clean_email(self):
    if 'email' in self.cleaned_data:
        email = self.cleaned_data['email']
        if not email.endswith('@web.conf.hu'):
            raise forms.ValidationError('Nem vagy szervező.')
        else:
            return email
from django import middlewares
process_request()    process_response()




process_view()      process_exception()
from django.http import HttpResponseRedirect

class LoginMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            if request.get_full_path() !=
                '/login/':
                return HttpResponseRedirect(
                    '/login/?next=%s' %
                    request.get_full_path())
            else:
                return None
from django.http import HttpResponseRedirect

class LoginMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            if request.get_full_path() !=
                '/login/':
                return HttpResponseRedirect(
                    '/login/?next=%s' %
                    request.get_full_path())
            else:
                return None
process_view(self, request,
             view_func, view_args, view_kwargs)

process_response(self, request, response)

process_exception(self, request, exception)
from django import test
doctest

class Conference(models.Model):
    """
    >>> v = Venue.objects.create(
            name='CEU', address='Budapest')
    >>> c = Conference.objects.create(
            Name='WebKonf', venue=v)
    >>> c.name
    u'WebKonf'
    >>> c.venue.name
    u'CEU'
    """
    name = models.CharField(max_length=32)
    venue = models.ForeignKey(Venue)
unittest

import unittest

class ConferenceTest(unittest.TestCase):
    def setUp(self):
        venue = Venue.objects.create(
            Name='CEU', address='Budapest')
        self.conf = Conference.objects.create(
            Name='WebKonf', venue=venue)

    def test_conference(self):
        self.assertEquals(self.conf.name,
                          u'WebKonf')
        self.assertEquals(self.conf.venue.name,
                          u'CEU')

    def tearDown(self):
        self.conf.delete()
from django.test import TestCase

-> kliens (GET, POST)

-> „hozzávalók” beemelése (JSON/XML dump)

-> egyedi url konfiguráció

-> e-mail fiók

-> további assert-ek
from django.test import TestCase

-> kliens (GET, POST)

def test_conference(self):
    response = self.client.get('/conf/1/')
    self.assertTrue('<h1>WebKonf</h1>' in
        response.content)
from django.test import TestCase

-> „hozzávalók” beemelése (JSON/XML dump)

class ConferenceTest(TestCase):
    fixtures = ['webkonf.json']

$ ./manage.py dumpdata conference > 
conference/fixtures/webkonf.json
from django.test import TestCase

-> egyedi url konfiguráció

class ConferenceTest(TestCase):
    urls = 'conference.test_urls'
from django.test import TestCase

-> e-mail fiók

from django.core import mail
def test_email(self):
    mail.send_mail('Subject', 'Message.',
        'from@web.conf.hu', ['jakab@gipsz.hu'],
        fail_silently=False)

    self.assertEquals(len(mail.outbox), 1)

    self.assertEquals(mail.outbox[0].subject,
                      'Subject')
from django.test import TestCase

-> további assert-ek

assertContains(response, text, count=None,
    status_code=200)

assertNotContains(response, text,
    status_code=200)

assertFormError(response, form, field, errors)

assertTemplateUsed(response, template_name)

assertTemplateNotUsed(response, template_name)

assertRedirects(response, expected_url,
    status_code=302, target_status_code=200)
$ python
from django.db import models
from django.contrib.localflavor.us.models import
    USStateField

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

class USVenue(Venue):
    state = USStateField(default='CA')

class ConferenceVenue(Venue):
    rooms = forms.PositiveIntegerField()
from django.db import models
from django.contrib.localflavor.us.models import
    USStateField

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

class USVenue(Venue):
    state = USStateField(default='CA')

class ConferenceVenue(Venue):
    rooms = forms.PositiveIntegerField()
from django.db import models
from django.contrib.localflavor.us.models import
    USStateField

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

class USVenue(Venue):
    state = USStateField(default='CA')

class ConferenceVenue(Venue):
    rooms = forms.PositiveIntegerField()
from django.db import models
from django.contrib.localflavor.us.models import
    USStateField

class Venue(models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=128)

    class Meta:
        abstract = True

class USVenue(Venue):
    state = USStateField(default='CA')

class ConferenceVenue(Venue):
    rooms = forms.PositiveIntegerField()
from django.contrib.auth.decorators import
    login_required

@login_required
def conference_private(request):
[...]

from django.utils.decorators import
    decorator_from_middleware
from conference.middleware.login import
    LoginMiddleware

login_required = decorator_from_middleware(
    LoginMiddleware)

@login_required
def conference_private(request):
[...]
from django.contrib.auth.decorators import
    login_required

@login_required
def conference_private(request):
[...]

from django.utils.decorators import
    decorator_from_middleware
from conference.middleware.login import
    LoginMiddleware

login_required = decorator_from_middleware(
    LoginMiddleware)

@login_required
def conference_private(request):
[...]
Modulok (csomagok)

__init__.py
conference/
    __init__.py
    models.py
    templates/
        conference.html
    views.py
manage.py
settings.py
urls.py
Modulok (csomagok)

__init__.py
conference/
    __init__.py
    models.py
    templates/
        conference.html
    views.py
manage.py
registration/
    [...]
settings.py
urls.py
Modulok (csomagok)

__init__.py
conference/
    __init__.py
    models.py
    templates/
        conference.html
    views/
        __init__.py
        attendees.py
        conferences.py
manage.py
registration/
    [...]
settings.py
urls.py
Globális/újrahasznosítható modulok

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'conference',
)
Globális/újrahasznosítható modulok

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'conference',
    'django_registration',
)
Globális/újrahasznosítható modulok

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'conference',
    'django_registration',
    'django_openid_auth',
)
Globális/újrahasznosítható modulok

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'conference',
    'django_registration',
    'django_openid_auth',
    'django_contact_form',
)
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^/conf/(?P<conf_id>d+)/$',
     'conference.views.conference_page'),
    (r'^openid/',
     include('django_openid_auth.urls')),
)
Globális/újrahasznosítható modulok

django-compressor
django-contact-form
django-db-log
django-debug-toolbar
django-extensions
django-flatblocks
django-gravatar
django-oembed
django-openid-auth
django-proxy
django-registration
django-tagging
django-timezones
django-tinymce
django-voting
django-wikiapp
Remixek

Pinax
(http://pinaxproject.com/)

37 django-*

Mingus
(http://github.com/montylounge/django-mingus/)

28 django-*
Hivatkozások

http://www.djangoproject.com/

http://docs.djangoproject.com/

http://gábor.20y.hu/django/
Django (Web Konferencia 2009)

Más contenido relacionado

La actualidad más candente

Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportAnton Arhipov
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICKonstantin Kudryashov
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Leonardo Soto
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIOJohn De Goes
 
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
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 ViewsEyal Vardi
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
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.0Eyal Vardi
 
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 PimpleHugo Hamon
 

La actualidad más candente (20)

Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience Report
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
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)
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
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
 
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
 

Similar a Django (Web Konferencia 2009)

Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)Mike Dirolf
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYCMike Dirolf
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009Ferenc Szalai
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access RunbookTaha Shakeel
 
Qualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio SimoniQualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio SimoniGrupo de Testes Carioca
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in AngularYadong Xie
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212Mahmoud Samir Fayed
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With RailsBoris Nadion
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 

Similar a Django (Web Konferencia 2009) (20)

Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Unit test
Unit testUnit test
Unit test
 
Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in Scala
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
Qualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio SimoniQualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio Simoni
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in Angular
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 

Último

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Último (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Django (Web Konferencia 2009)

  • 1. Farkas Szilveszter Magyarországi Web Konferencia Budapest, 2009. október 3.
  • 6. from presentation import (Django, Forms, Middleware, Tests, Python)
  • 7. >>> import django >>> django.ORIGINAL_AUTHOR 'Adrian Holovaty' >>> django.OPEN_SOURCED datetime.date(2005, 7, 13) >>> django.VERSION '1.1-final' >>> len(django.AUTHORS) 485
  • 8. >>> import django >>> django.ORIGINAL_AUTHOR 'Adrian Holovaty' >>> django.OPEN_SOURCED datetime.date(2005, 7, 13) >>> django.VERSION '1.1-final' >>> len(django.AUTHORS) 485
  • 9. >>> import django >>> django.ORIGINAL_AUTHOR 'Adrian Holovaty' >>> django.OPEN_SOURCED datetime.date(2005, 7, 13) >>> django.VERSION '1.1-final' >>> len(django.AUTHORS) 485
  • 10. >>> import django >>> django.ORIGINAL_AUTHOR 'Adrian Holovaty' >>> django.OPEN_SOURCED datetime.date(2005, 7, 13) >>> django.VERSION '1.1-final' >>> len(django.AUTHORS) 485
  • 11. >>> import django >>> django.ORIGINAL_AUTHOR 'Adrian Holovaty' >>> django.OPEN_SOURCED datetime.date(2005, 7, 13) >>> django.VERSION '1.1-final' >>> len(django.AUTHORS) 485
  • 13. $ django-admin startproject webkonf $ cd webkonf $ ./manage.py startapp conference
  • 14. from django.db import models class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class Conference(models.Model): name = models.CharField(max_length=32) venue = models.ForeignKey(ConferenceVenue) from django.contrib.auth.models import User class Attendee(models.Model): user = models.OneToOneField(User) conferences = models.ManyToManyField( Conference, related_name='attendees')
  • 15. from django.db import models class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class Conference(models.Model): name = models.CharField(max_length=32) venue = models.ForeignKey(Venue) from django.contrib.auth.models import User class Attendee(models.Model): user = models.OneToOneField(User) conferences = models.ManyToManyField( Conference, related_name='attendees')
  • 16. from django.db import models class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class Conference(models.Model): name = models.CharField(max_length=32) venue = models.ForeignKey(Venue) from django.contrib.auth.models import User class Attendee(models.Model): user = models.OneToOneField(User) conferences = models.ManyToManyField( Conference, related_name='attendees')
  • 17. [...] <h1>{{ conference.name }}</h1> <h2>Látogatók</h2> <ul> {% for attendee in conference.attendees.all %} <li>{{ attendee.user.get_full_name }}</li> {% endfor %} </ul> [...]
  • 18. from django.shortcuts import (get_object_or_404, render_to_response) from conference.models import Conference def conference_page(request, conf_id): conference = get_object_or_404( Conference, pk=conf_id) context = { 'conference': conference } return render_to_response( 'conference.html', context)
  • 19. from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^/conf/(?P<conf_id>d+)/$', 'conference.views.conference_page'), )
  • 20.
  • 24. Űrlap osztály class AttendeeForm(forms.Form): Mező name = forms.CharField('Név', max_length=32) Widget password = forms.CharField( 'Jelszó', max_length=32, widget=forms.PasswordInput())
  • 25. Űrlap osztály class AttendeeForm(forms.Form): Mező name = forms.CharField('Név', max_length=32) Widget password = forms.CharField( 'Jelszó', max_length=32, widget=forms.PasswordInput())
  • 26. Űrlap osztály class AttendeeForm(forms.Form): Mező name = forms.CharField('Név', max_length=32) Widget password = forms.CharField( 'Jelszó', max_length=32, widget=forms.PasswordInput())
  • 27. Beépített ellenőrzés email = forms.EmailField(max_length=75) zip = forms.IntegerField(min_value=1000, max_value=9999) Mezőszintű egyedi ellenőrzés def clean_FIELDNAME(self): Űrlapszintű egyedi ellenőrzés def clean(self):
  • 28. Beépített ellenőrzés email = forms.EmailField(max_length=75) zip = forms.IntegerField(min_value=1000, max_value=9999) Mezőszintű egyedi ellenőrzés def clean_FIELDNAME(self): Űrlapszintű egyedi ellenőrzés def clean(self):
  • 29. Beépített ellenőrzés email = forms.EmailField(max_length=75) zip = forms.IntegerField(min_value=1000, max_value=9999) Mezőszintű egyedi ellenőrzés def clean_FIELDNAME(self): Űrlapszintű egyedi ellenőrzés def clean(self):
  • 30. Mezőszintű egyedi ellenőrzés def clean_email(self): if 'email' in self.cleaned_data: email = self.cleaned_data['email'] if not email.endswith('@web.conf.hu'): raise forms.ValidationError('Nem vagy szervező.') else: return email
  • 31. from django import middlewares
  • 32.
  • 33. process_request() process_response() process_view() process_exception()
  • 34. from django.http import HttpResponseRedirect class LoginMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): if request.get_full_path() != '/login/': return HttpResponseRedirect( '/login/?next=%s' % request.get_full_path()) else: return None
  • 35. from django.http import HttpResponseRedirect class LoginMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): if request.get_full_path() != '/login/': return HttpResponseRedirect( '/login/?next=%s' % request.get_full_path()) else: return None
  • 36. process_view(self, request, view_func, view_args, view_kwargs) process_response(self, request, response) process_exception(self, request, exception)
  • 38. doctest class Conference(models.Model): """ >>> v = Venue.objects.create( name='CEU', address='Budapest') >>> c = Conference.objects.create( Name='WebKonf', venue=v) >>> c.name u'WebKonf' >>> c.venue.name u'CEU' """ name = models.CharField(max_length=32) venue = models.ForeignKey(Venue)
  • 39. unittest import unittest class ConferenceTest(unittest.TestCase): def setUp(self): venue = Venue.objects.create( Name='CEU', address='Budapest') self.conf = Conference.objects.create( Name='WebKonf', venue=venue) def test_conference(self): self.assertEquals(self.conf.name, u'WebKonf') self.assertEquals(self.conf.venue.name, u'CEU') def tearDown(self): self.conf.delete()
  • 40. from django.test import TestCase -> kliens (GET, POST) -> „hozzávalók” beemelése (JSON/XML dump) -> egyedi url konfiguráció -> e-mail fiók -> további assert-ek
  • 41. from django.test import TestCase -> kliens (GET, POST) def test_conference(self): response = self.client.get('/conf/1/') self.assertTrue('<h1>WebKonf</h1>' in response.content)
  • 42. from django.test import TestCase -> „hozzávalók” beemelése (JSON/XML dump) class ConferenceTest(TestCase): fixtures = ['webkonf.json'] $ ./manage.py dumpdata conference > conference/fixtures/webkonf.json
  • 43. from django.test import TestCase -> egyedi url konfiguráció class ConferenceTest(TestCase): urls = 'conference.test_urls'
  • 44. from django.test import TestCase -> e-mail fiók from django.core import mail def test_email(self): mail.send_mail('Subject', 'Message.', 'from@web.conf.hu', ['jakab@gipsz.hu'], fail_silently=False) self.assertEquals(len(mail.outbox), 1) self.assertEquals(mail.outbox[0].subject, 'Subject')
  • 45. from django.test import TestCase -> további assert-ek assertContains(response, text, count=None, status_code=200) assertNotContains(response, text, status_code=200) assertFormError(response, form, field, errors) assertTemplateUsed(response, template_name) assertTemplateNotUsed(response, template_name) assertRedirects(response, expected_url, status_code=302, target_status_code=200)
  • 47. from django.db import models from django.contrib.localflavor.us.models import USStateField class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class USVenue(Venue): state = USStateField(default='CA') class ConferenceVenue(Venue): rooms = forms.PositiveIntegerField()
  • 48. from django.db import models from django.contrib.localflavor.us.models import USStateField class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class USVenue(Venue): state = USStateField(default='CA') class ConferenceVenue(Venue): rooms = forms.PositiveIntegerField()
  • 49. from django.db import models from django.contrib.localflavor.us.models import USStateField class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class USVenue(Venue): state = USStateField(default='CA') class ConferenceVenue(Venue): rooms = forms.PositiveIntegerField()
  • 50. from django.db import models from django.contrib.localflavor.us.models import USStateField class Venue(models.Model): name = models.CharField(max_length=64) address = models.CharField(max_length=128) class Meta: abstract = True class USVenue(Venue): state = USStateField(default='CA') class ConferenceVenue(Venue): rooms = forms.PositiveIntegerField()
  • 51. from django.contrib.auth.decorators import login_required @login_required def conference_private(request): [...] from django.utils.decorators import decorator_from_middleware from conference.middleware.login import LoginMiddleware login_required = decorator_from_middleware( LoginMiddleware) @login_required def conference_private(request): [...]
  • 52. from django.contrib.auth.decorators import login_required @login_required def conference_private(request): [...] from django.utils.decorators import decorator_from_middleware from conference.middleware.login import LoginMiddleware login_required = decorator_from_middleware( LoginMiddleware) @login_required def conference_private(request): [...]
  • 53. Modulok (csomagok) __init__.py conference/ __init__.py models.py templates/ conference.html views.py manage.py settings.py urls.py
  • 54. Modulok (csomagok) __init__.py conference/ __init__.py models.py templates/ conference.html views.py manage.py registration/ [...] settings.py urls.py
  • 55. Modulok (csomagok) __init__.py conference/ __init__.py models.py templates/ conference.html views/ __init__.py attendees.py conferences.py manage.py registration/ [...] settings.py urls.py
  • 56. Globális/újrahasznosítható modulok INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'conference', )
  • 57. Globális/újrahasznosítható modulok INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'conference', 'django_registration', )
  • 58. Globális/újrahasznosítható modulok INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'conference', 'django_registration', 'django_openid_auth', )
  • 59. Globális/újrahasznosítható modulok INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'conference', 'django_registration', 'django_openid_auth', 'django_contact_form', )
  • 60. from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^/conf/(?P<conf_id>d+)/$', 'conference.views.conference_page'), (r'^openid/', include('django_openid_auth.urls')), )