View All Posts. MiCHiLU.com powered by Django ;-)

[Django][DEMO]: Django勉強会 Disc 2

Django オンラインドキュメント和訳:
http://ymasuda.jp/python/django/docs/index.html

1. Django Project/App を作成する

$ django-admin.py startproject myproject

$ cd myproject
$ chmod 755 manage.py
$ ./manage.py startapp blog

$ mkdir -p templates/blog

2. Django Project を設定する

myproject/settings.py

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '../db/myproject.db'

import os
TEMPLATE_DIRS = (
    #"/full-path-to/myproject/templates",
    os.path.abspath('templates').replace(os.sep, "/"),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',

    "django.contrib.admin", ####
    "myproject.blog",       ####
)

:

"django.contrib.admin"
管理画面(Django Administration Site)を有効化する。
"myproject.blog"
Django App のインストール。

3. Django App - Model

myproject/blog/models.py

from django.db import models

class Entry(models.Model):
    content = models.TextField(blank=True)
    add_date = models.DateTimeField(auto_now_add=True, editable=False)
    mod_date = models.DateTimeField(auto_now=True, editable=False)

    class Admin:    ####
        pass

:

class Admin:
管理画面での編集を有効にする。

4. データベースを作成する

$ mkdir ../db
$ touch ../db/myproject.db
$ ./manage.py syncdb
...
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'endoh'):
E-mail address: spam@ham.egg
Password: ****
Password (again): ****
Superuser created successfully.
...

5. 開発サーバを起動する

$ ./manage.py runserver
Validating models...
0 errors found.

Django version 0.96-pre, using settings 'myproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

6. Django Administration

http://127.0.0.1:8000/admin/

myproject.urls.py

urlpatterns = patterns('',
    # Example:
    # (r'^myproject/', include('myproject.foo.urls')),

    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')), ####
)

コメントアウトを外す。

7. Database API

$ ./manage.py shell
>>> from myproject.blog.models import Entry

>>> Entry.objects.count()
1

>>> Entry.objects.all()
[<Entry: Entry object>]

>>> Entry.objects.all()[1].content
'content text'

8. Generic View

汎用ビュー:
http://ymasuda.jp/python/django/docs/generic_views.html

django.views.generic.list_detail.object_list

myproject/urls.py

from django.conf.urls.defaults import *
from myproject.blog.models import Entry

urlpatterns = patterns('',
    # Example:
    # (r'^myproject/', include('myproject.foo.urls')),

    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
)

####
urlpatterns += patterns('django.views.generic.list_detail',
    (r'^$', "object_list", {
        "queryset": Entry.objects.order_by("-add_date")[:3],
        #"template_name": "blog/entry_list.html",
    }),
)
####

9. テンプレートタグ

テンプレート作者のための Django テンプレート言語ガイド:
http://ymasuda.jp/python/django/docs/templates.html

myproject/templates/blog/entry_list.html

{% for object in object_list %}
    {{ object.content }}
{% endfor %}

10. テンプレートの継承

http://ymasuda.jp/python/django/docs/templates.html#id6

myproject/templates/blog/entry_list.html

{% extends "base.html" %}

{% block content %}
    <ul>
    {% for object in object_list %}
        <li>
        {{ object.content|slice:"20" }}
         -
        {{ object.add_date|date:"r" }}
        <a href="/blog/entry/{{ object.id }}/">[Read]</a>
        </li>
    {% endfor %}
    </ul>
{% endblock %}

myproject/templates/base.html

<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

11. URL configuration

URL ディスパッチャ:
http://ymasuda.jp/python/django/docs/url_dispatch.html

myproject/urls.py

from django.conf.urls.defaults import *
from myproject.blog.models import Entry

urlpatterns = patterns('',
    # Example:
    ####
    (r'^blog/', include('myproject.blog.urls')),
    ####

    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
)

urlpatterns += patterns('django.views.generic.list_detail',
    (r'^$', "object_list", {
        "queryset": Entry.objects.order_by("-add_date")[:3],
        #"template_name": "blog/entry_list.html",
    }),
)

:

myproject.blog.urls をルールを "/blog/" に割り当てる。

12. Generic View

django.views.generic.list_detail.object_detail

myproject/blog/urls.py

from django.conf.urls.defaults import *
from myproject.blog.models import Entry

urlpatterns = patterns('django.views.generic.list_detail',
    (r"^entry/(?P<object_id>\d+)/$",
        "object_detail", {"queryset": Entry.objects.all(),
        #"template_name": "blog/entry_detail.html",
    }),
)

myproject/templates/entry_detail.html

{% load markup %}
{% extends "base.html" %}

{% block title %}
    {{ object.title }}
{% endblock %}

{% block content %}
    {{ object.content|restructuredtext }}
    {{ object.add_date|date:"r" }}
    <a href="/">[Back]</a>
{% endblock %}

13. contrib テンプレートライブラリ

django.contrib.markup

myproject/settings.py

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',

    "django.contrib.admin",
    "myproject.blog",

    "django.contrib.markup",
)

myproject/sessions.py

RESTRUCTUREDTEXT_FILTER_SETTINGS = {
    'doctitle_xform': False,
}

myproject/blog/models.py

from django.db import models

class Entry(models.Model):
    content = models.TextField(blank=True)
    add_date = models.DateTimeField(auto_now_add=True)
    mod_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.content.split("\r\n")[0]

    title = property(__str__)

    class Admin:
        pass

14. Syndication feeds (RSS and Atom)

配信フィードフレームワーク:
http://ymasuda.jp/python/django/docs/syndication_feeds.html

myproject/urls.py

...
from myproject.feeds import *

...

feeds = {
    'atom': LatestEntries_atom,
    'rss': LatestEntries_rss,
    'rdf': LatestEntries_rdf,
}

urlpatterns += patterns('django.contrib.syndication.views',
    (r'^feeds/(?P<url>.*)/', 'feed', {'feed_dict': feeds}),
)

myproject/feeds.py

from django.contrib.syndication.feeds import Feed
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed, \
                                                    RssUserland091Feed
from myproject.blog.models import Entry

class LatestEntries_atom(Feed):
    feed_type = Atom1Feed
    title = "Site Title"
    link = "/"
    description = "Site Description"
    #title_template = "feeds/blog_title.html"
    #description_template = "feeds/blog_description.html"

    def items(self):
        return Entry.objects.order_by('-add_date')[:20]

    def item_link(self, obj):
        return "/blog/entry/%s/" % obj.id

    def item_pubdate(self, obj):
        return obj.add_date


class LatestEntries_rss(LatestEntries_atom):
    feed_type = Rss201rev2Feed


class LatestEntries_rdf(LatestEntries_atom):
    feed_type = RssUserland091Feed

15. Sitemaps

sitemaps フレームワーク:
http://ymasuda.jp/python/django/docs/sitemaps.html

myproject/settings.py

...

INSTALLED_APPS = (
    ...

    "django.contrib.sitemaps",
)

myproject/utils.py

...
from myproject.sitemaps import sitemaps

...

urlpatterns = patterns('',
    ...

    (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap',
        {'sitemaps': sitemaps}
    ),
)

myproject/sitemaps.py

from django.contrib.sitemaps import GenericSitemap
from myproject.blog.models import Entry

info_dict = {
    "queryset": Entry.objects.all(),
    "date_field": "mod_date",
}

class BlogSitemap(GenericSitemap):
    def location(self, obj):
        return "/blog/entry/%s/" % obj.id

sitemaps = {
    "blog": BlogSitemap(info_dict, priority=0.6),
}
Sat, 20 Jan 2007 16:46:19 +0900 source edit
Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.1 Japan License.
View All Posts. MiCHiLU.com powered by Django ;-)