Django

     Szalai Ferenc
(szferi@wsbricks.com)
Bevezetés
“Django egy magas szintű Python
    nyelven írt web alkalmazás
   keretrendszer, ami a gyors és
pragmatikus alkalmazás fejlesztést
            támogatja.”
Telepítés
előfeltétel: python, django forrás
(svn, tar.gz)
# cd django
# python setup.py install
http://www.djangoproject.com/documentation/install/
Alapfogalmak
●   Projekt
●   Alkalmazas
●   Model
●   View
●   Controller (URL)
●   Template
$ django-admin.py startproject supporter
$ ls -l supporter/

__init__.py
manage.py
settings.py
urls.py
$ python manage.py runserver
Validating models...
0 errors found

Django version 1.1 beta 1, using
settings 'supporter.settings'
Development server is running at
http://127.0.0.1:8000/
Quit the server with CONTROL-C.
settings.py
●   DATABASE_ENGINE
●   DATABASE_NAME
●   DATABASE_USER
●   DATABASE_PASSWORD
●   DATABASE_HOST
●   normál python modul
●   a saját konfig paramétereink legyenek
    nagybetűsek!
●   http://www.djangoproject.com/documentation/settings/
Alkalmazások
● logikai egység
● újrafelhasználható


● összetartozó model, view, url

  gyűjteménye
●   $ python manage.py startapp topic
$ ls topic/
__init__.py
models.py
tests.py
views.py
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'supporter.topic'
)
User




                                 Company




django.contrib.auth
                                  Topic
                                    Topic
       djangon.contrib.comment           Topic




             Comment              supporter.topic

                 Comment
Model
BEGIN;
CREATE TABLE "topic_topic" (
    "id" integer NOT NULL PRIMARY KEY,
    "author_id" integer NOT NULL,
    "type" varchar(1) NOT NULL,
    "title" varchar(128) NOT NULL,
    "content" text NOT NULL,
    "feeling" integer NOT NULL
)
;
COMMIT;
Az SQL csúnya
 A Python cool
from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):

    TOPIC_TYPES = (
        ('Q', 'Question'),
        ('I', 'Idea'),
        ('P', 'Problem'),
    )

    author = models.ForeignKey(User)
    type = models.CharField(max_length=1,
                          choices=TOPIC_TYPES)
    title = models.CharField(max_length=128)
    content = models.TextField()
    feeling = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)
$ python   manage.py validate
$ python   manage.py syncdb
Creating   table auth_permission
Creating   table auth_group
Creating   table auth_user
Creating   table auth_message
Creating   table django_content_type
Creating   table django_session
Creating   table django_site
Creating   table topic_topic

You just installed Django's auth system, which
means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'szferi'):
E-mail address: szferi@wsbricks.com
Password:
Password (again):
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Message model
Installing index for topic.Topic model
Model API
$ python manage.py shell
In [1]: from supporter.topic.models import Topic
In [2]: from django.contrib.auth.models import User
In [3]: u = User.objects.get(id=1)
In [4]: print u
szferi

In [5]: t = Topics.objects.create(author=u, type='Q',
title='test', content='nagybaj!', feeling=-1)
In [6]: print t
Topic object

In [7]: print t.title
test

In [8]: print Topic.objects.all()
[<Topic: Topic object>]
In [9]: ts = Topic.objects.filter(content__contains='baj')
In [10]: print ts[0].content
nagybaj!
class Topic(models.Model):
    ...

   def __unicode__(self):
       return self.title
$ python manage.py shell
In [1]: from supporter.topic.models import Topic
In [2]: print Topic.objects.all()
[<Topic: test>]
class Topic(models.Model):
    ...

   class Meta:
       ordering = ['created']
Relációk
from django.db import models
from django.contrib.auth.models import User

class Topic(models.Model):

    TOPIC_TYPES = (
        ('Q', 'Question'),
        ('I', 'Idea'),
        ('P', 'Problem'),
    )

    author = models.ForeignKey(User)
    type = models.CharField(max_length=1,
                          choices=TOPIC_TYPES)
    title = models.CharField(max_length=128)
    content = models.TextField()
    feeling = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)
$ python manage.py shell
In [2]: from django.contrib.auth.models import User
In [3]: u = User.objects.get(id=1)
In [4]: print u
szferi

In [5]: print u.topic_set.all()
[<Topic: test>]

In [6]: print u.topic_set.filter(type='Q')
[<Topic: test>]
Views
from django.http import HttpResponse

def index(request):
    return HttpResponse('Hello!')
intermezzó: URL
/customer/account/1/contacts/2/
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
    (r'^$', views.index),
    (r'^(?P<topic>[0-9]*)/$', views.detail)
)
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^topic/', include('supporter.topic.urls')),
)
Összetettebb View-k
from django.http import
HttpResponse
from supporter.topic.models
import Topic

def index(request):
    r = '<ul>'
    topics = Topic.objects.all()
    for t in topics:
        r += "<li>%s</li>" % 
                        t.title
    r += '</ul>'
    return HttpResponse(r)
intermezzó 2: Tempalte
<html>
<body>
<p>There is {{ topics|length }} topics</p>
<ul>
{% for t in topics %}
   <li>{{ t.title }}</li>
{% endfor %}
</ul>
</body>
</html>
Django Admin
from django.conf.urls.defaults import *
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^topic/', include('supporter.topic.urls')),
)
Formok
from models import Topic
from django.forms import ModelForm

class TopicForm(ModelForm):
    class Meta:
        model = Topic
        exclude = ('author', )
def add(request):
    from forms import TopicForm
    from django.http import HttpResponseRedirect
    from django.contrib.auth.models import User

    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid():
            topic = form.save(commit=False)
            topic.author = User.objects.get(id=1)
            topic.save()
            return HttpResponseRedirect('/')
    else:
        form = TopicForm()
    return render_to_response('add.html',
{'form': form })
<html>
<body>
<form method="post" action=".">
{{ form }}
<input type="submit" value="SAVE"
name="save"/>
</form>
</body>
</html>
Hova tovább, hovatovább
●   automatikus teszt
●   saját template tag és filter
●   session kezelés
●   authentikáció
●   cache
●   l10n, i18n
●   RSS/Atom
●   Generikus view-k
●   stb, stb.
Django tutorial 2009

Django tutorial 2009

  • 1.
    Django Szalai Ferenc (szferi@wsbricks.com)
  • 2.
  • 3.
    “Django egy magasszintű Python nyelven írt web alkalmazás keretrendszer, ami a gyors és pragmatikus alkalmazás fejlesztést támogatja.”
  • 4.
  • 5.
    előfeltétel: python, djangoforrás (svn, tar.gz) # cd django # python setup.py install http://www.djangoproject.com/documentation/install/
  • 6.
    Alapfogalmak ● Projekt ● Alkalmazas ● Model ● View ● Controller (URL) ● Template
  • 7.
  • 8.
    $ ls -lsupporter/ __init__.py manage.py settings.py urls.py
  • 9.
    $ python manage.pyrunserver Validating models... 0 errors found Django version 1.1 beta 1, using settings 'supporter.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
  • 10.
    settings.py ● DATABASE_ENGINE ● DATABASE_NAME ● DATABASE_USER ● DATABASE_PASSWORD ● DATABASE_HOST ● normál python modul ● a saját konfig paramétereink legyenek nagybetűsek! ● http://www.djangoproject.com/documentation/settings/
  • 11.
    Alkalmazások ● logikai egység ●újrafelhasználható ● összetartozó model, view, url gyűjteménye ● $ python manage.py startapp topic
  • 12.
  • 13.
    INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'supporter.topic' )
  • 14.
    User Company django.contrib.auth Topic Topic djangon.contrib.comment Topic Comment supporter.topic Comment
  • 15.
  • 16.
    BEGIN; CREATE TABLE "topic_topic"( "id" integer NOT NULL PRIMARY KEY, "author_id" integer NOT NULL, "type" varchar(1) NOT NULL, "title" varchar(128) NOT NULL, "content" text NOT NULL, "feeling" integer NOT NULL ) ; COMMIT;
  • 17.
    Az SQL csúnya A Python cool
  • 18.
    from django.db importmodels from django.contrib.auth.models import User class Topic(models.Model): TOPIC_TYPES = ( ('Q', 'Question'), ('I', 'Idea'), ('P', 'Problem'), ) author = models.ForeignKey(User) type = models.CharField(max_length=1, choices=TOPIC_TYPES) title = models.CharField(max_length=128) content = models.TextField() feeling = models.IntegerField() created = models.DateTimeField(auto_now_add=True)
  • 19.
    $ python manage.py validate $ python manage.py syncdb Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_content_type Creating table django_session Creating table django_site Creating table topic_topic You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): yes Username (Leave blank to use 'szferi'): E-mail address: szferi@wsbricks.com Password: Password (again): Superuser created successfully. Installing index for auth.Permission model Installing index for auth.Message model Installing index for topic.Topic model
  • 20.
  • 21.
    $ python manage.pyshell In [1]: from supporter.topic.models import Topic In [2]: from django.contrib.auth.models import User In [3]: u = User.objects.get(id=1) In [4]: print u szferi In [5]: t = Topics.objects.create(author=u, type='Q', title='test', content='nagybaj!', feeling=-1) In [6]: print t Topic object In [7]: print t.title test In [8]: print Topic.objects.all() [<Topic: Topic object>] In [9]: ts = Topic.objects.filter(content__contains='baj') In [10]: print ts[0].content nagybaj!
  • 22.
    class Topic(models.Model): ... def __unicode__(self): return self.title
  • 23.
    $ python manage.pyshell In [1]: from supporter.topic.models import Topic In [2]: print Topic.objects.all() [<Topic: test>]
  • 24.
    class Topic(models.Model): ... class Meta: ordering = ['created']
  • 25.
  • 26.
    from django.db importmodels from django.contrib.auth.models import User class Topic(models.Model): TOPIC_TYPES = ( ('Q', 'Question'), ('I', 'Idea'), ('P', 'Problem'), ) author = models.ForeignKey(User) type = models.CharField(max_length=1, choices=TOPIC_TYPES) title = models.CharField(max_length=128) content = models.TextField() feeling = models.IntegerField() created = models.DateTimeField(auto_now_add=True)
  • 27.
    $ python manage.pyshell In [2]: from django.contrib.auth.models import User In [3]: u = User.objects.get(id=1) In [4]: print u szferi In [5]: print u.topic_set.all() [<Topic: test>] In [6]: print u.topic_set.filter(type='Q') [<Topic: test>]
  • 28.
  • 29.
    from django.http importHttpResponse def index(request): return HttpResponse('Hello!')
  • 30.
  • 33.
  • 34.
    from django.conf.urls.defaults import* import views urlpatterns = patterns('', (r'^$', views.index), (r'^(?P<topic>[0-9]*)/$', views.detail) )
  • 35.
    from django.conf.urls.defaults import* urlpatterns = patterns('', (r'^topic/', include('supporter.topic.urls')), )
  • 36.
  • 37.
    from django.http import HttpResponse fromsupporter.topic.models import Topic def index(request): r = '<ul>' topics = Topic.objects.all() for t in topics: r += "<li>%s</li>" % t.title r += '</ul>' return HttpResponse(r)
  • 38.
  • 39.
    <html> <body> <p>There is {{topics|length }} topics</p> <ul> {% for t in topics %} <li>{{ t.title }}</li> {% endfor %} </ul> </body> </html>
  • 41.
  • 42.
    from django.conf.urls.defaults import* from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^topic/', include('supporter.topic.urls')), )
  • 45.
  • 46.
    from models importTopic from django.forms import ModelForm class TopicForm(ModelForm): class Meta: model = Topic exclude = ('author', )
  • 47.
    def add(request): from forms import TopicForm from django.http import HttpResponseRedirect from django.contrib.auth.models import User if request.method == 'POST': form = TopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.author = User.objects.get(id=1) topic.save() return HttpResponseRedirect('/') else: form = TopicForm() return render_to_response('add.html', {'form': form })
  • 48.
    <html> <body> <form method="post" action="."> {{form }} <input type="submit" value="SAVE" name="save"/> </form> </body> </html>
  • 49.
    Hova tovább, hovatovább ● automatikus teszt ● saját template tag és filter ● session kezelés ● authentikáció ● cache ● l10n, i18n ● RSS/Atom ● Generikus view-k ● stb, stb.