Table of Contents
หน้านี้รวบรวมลิงก์และโค้ดสำหรับการสอน Django เพิ่มเติมในส่วนของ ORM
- ดาวน์โหลด Django Django1.3 mirror at ku
โปรแกรมหมู่เช้า
โปรแกรมหมู่บ่าย
แก้ settings.py
ตัด middle ware ของระบบ CSRF protection ออก โดย comment บรรทัด 'django.middleware.csrf.CsrfViewMiddleware',
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', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
events/models.py
from django.db import models class Event(models.Model): title = models.CharField(max_length=200) place = models.CharField(max_length=100) def __unicode__(self): return self.title class Comment(models.Model): event = models.ForeignKey('Event') body = models.CharField(max_length=500) def __unicode__(self): return self.body
urls.py
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # url(r'^$', 'ievents.views.home', name='home'), url(r'^$', 'ievents.events.views.list'), url(r'^post_comment/(\d+)/$', 'ievents.events.views.create_comment'), url(r'^admin/', include(admin.site.urls)), )
events/views.py
from models import Event, Comment from django.shortcuts import render_to_response, redirect def list(request): events = Event.objects.all() return render_to_response("list.html", {'events': events}) def create_comment(request,event_id): event = Event.objects.get(pk=event_id) comment = Comment() comment.body = request.POST['body'] comment.event = event comment.save() return redirect('/')
events/templates/list.html
<html> <body> <h1>List of events</h1> {% for e in events %} <b>{{ e.title }}</b> - <small>{{ e.place }}</small><br /> <ul> {% for c in e.comment_set.all %} <li>{{ c.body }}</li> {% endfor %} </ul> <form action="/post_comment/{{ e.id }}/" method="post"> New comment: <textarea name="body"></textarea> <input type="submit" value="Post comment"/> </form> {% endfor %} </body> </html>
events/admin.py
from models import Event from django.contrib import admin admin.site.register(Event)