Commits

Shinya Okano committed 09f510a

最初のコミット

Comments (0)

Files changed (13)

+syntax:glob
+*.pyc
+*.swp
+*.orig
+*.db

myproject/__init__.py

Empty file added.

myproject/guestbook/__init__.py

Empty file added.

myproject/guestbook/admin.py

+# coding: utf8
+from django.contrib import admin
+
+from guestbook.models import Greeting
+
+class GreetingAdmin(admin.ModelAdmin):
+    list_display = ('__unicode__', 'username', 'create_at')
+    list_filter = ('create_at', 'username')
+    search_fields = ('username', 'content')
+
+# Adminサイトへ登録する
+admin.site.register(Greeting, GreetingAdmin)

myproject/guestbook/forms.py

+# coding: utf8
+from django import forms
+
+from guestbook.models import Greeting
+
+class GreetingForm(forms.ModelForm):
+    """
+    ゲストブックの書き込みフォーム
+    モデルを元に生成する
+    """
+    class Meta:
+        model = Greeting
+ 
+        # 書き込み日時は除く
+        exclude = ('create_at',)
+
+class GreetingForm2(forms.ModelForm):
+    """
+    ModelFormを使わない場合
+    """
+    username = forms.CharField(max_length=30)
+    content = forms.CharField(max_length=1000, widget=forms.Textarea)

myproject/guestbook/models.py

+# coding: utf8
+from datetime import datetime
+
+from django.db import models
+
+class Greeting(models.Model):
+    """
+    ゲストブックのコンテンツのモデル
+    """
+    username = models.CharField(u'名前', max_length=30)
+    content = models.TextField(u'書き込み内容', max_length=1000)
+    create_at = models.DateTimeField(u'書き込み日時', default=datetime.now)
+
+    def __unicode__(self):
+        """
+        モデルの文字列表現
+        内容の改行を削除して先頭から20文字を返す
+        """
+        return ''.join(unicode(self.content).splitlines())[:20]
+
+    class Meta:
+        # ソート順
+        ordering = ('-create_at',)
+        # 単数形
+        verbose_name = u'書き込み'
+        # 複数形
+        verbose_name_plural = u'書き込み'

myproject/guestbook/templates/guestbook/base.html

+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
+  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html>
+  <head>
+    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+    <title>{% block title %}{% endblock %}</title>
+  </head>
+  <body>
+    <div id="main">{% block main %}{% endblock %}</div>
+  </body>
+</html>

myproject/guestbook/templates/guestbook/greeting_form.html

+{% extends "guestbook/base.html" %}
+
+{% block title %}ゲストブック{% endblock %}
+
+{% block main %}
+<h1>ゲストブック</h1>
+<p>書き込みをどうぞ。</p>
+<form action="{% url guestbook_index %}" method="post">
+  {% csrf_token %}
+  <table>{{ form.as_table }}</table>
+  <p><button type="submit">送信</button></p>
+</form>
+<h2>これまでの書き込み</h2>
+<div>
+  {% for greeting in greeting_list %}
+    <h3>{{ greeting.username }} さんの書き込み({{ greeting.create_at }}):</h3>
+    <p>{{ greeting.content|linebreaksbr }}</p>
+  {% endfor %}
+</div>
+{% endblock %}

myproject/guestbook/urls.py

+from django.conf.urls.defaults import *
+
+urlpatterns = patterns('',
+    url(r'^$', 'guestbook.views.index', name='guestbook_index'),
+)

myproject/guestbook/views.py

+# coding: utf8
+from django.http import HttpResponse, HttpResponseRedirect
+from django.core.urlresolvers import reverse
+from django.views.generic.create_update import create_object
+from django.template import Template, RequestContext
+from django.template.loader import render_to_string
+
+from guestbook.models import Greeting
+from guestbook.forms import GreetingForm
+
+def index(request):
+    # 汎用ビューを利用
+    return create_object(request,
+                         form_class=GreetingForm,
+                         post_save_redirect=reverse('guestbook_index'),
+                         extra_context={'greeting_list': Greeting.objects.all()})
+
+def index2(request):
+    # 汎用ビューをを使わない場合
+    # フォームオブジェクトを作成して入力内容の検証
+    form = GreetingForm(request.POST or None)
+    if form.is_valid():
+        # 内容を保存してリダイレクト
+        form.save()
+        return HttpResponseRedirect(reverse('guestbook_index'))
+    # コンテキストを作成
+    context = RequestContext(request)
+    context['greeting_list'] = Greeting.objects.all()
+    context['form'] = form
+    # レンダリングしてページを表示
+    return HttpResponse(render_to_string('guestbook/greeting_form.html', context))

myproject/manage.py

+#!/usr/bin/env python
+from django.core.management import execute_manager
+try:
+    import settings # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    sys.exit(1)
+
+if __name__ == "__main__":
+    execute_manager(settings)

myproject/settings.py

+# Django settings for myproject project.
+import os
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+    # ('Your Name', 'your_email@domain.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+        'NAME': os.path.join(BASE_DIR, 'myproject.db'),                      # Or path to database file if using sqlite3.
+        'USER': '',                      # Not used with sqlite3.
+        'PASSWORD': '',                  # Not used with sqlite3.
+        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
+        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
+    }
+}
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# On Unix systems, a value of None will cause Django to use the same
+# timezone as the operating system.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'Asia/Tokyo'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'ja'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# If you set this to False, Django will not format dates, numbers and
+# calendars according to the current locale
+USE_L10N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = ''
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_URL = ''
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/", "/media/".
+ADMIN_MEDIA_PREFIX = '/media/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = 'aqxib^_^oj!#o_q6qkob-a-u-6ci+5#_8^y#tddx^f5&9w@i)h'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.Loader',
+    'django.template.loaders.app_directories.Loader',
+#     'django.template.loaders.eggs.Loader',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+)
+
+ROOT_URLCONF = 'myproject.urls'
+
+TEMPLATE_DIRS = (
+    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+    # Always use forward slashes, even on Windows.
+    # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'django.contrib.messages',
+    'django.contrib.admin',
+    'guestbook',
+)

myproject/urls.py

+from django.conf.urls.defaults import *
+from django.contrib import admin
+admin.autodiscover()
+
+urlpatterns = patterns('',
+    (r'^admin/', include(admin.site.urls)),
+    (r'', include('guestbook.urls')),
+)