หน้านี้รวบรวมลิงก์และโค้ดสำหรับการสอน Django เพิ่มเติมในส่วนของ ORM
* ดาวน์โหลด Django [[http://www.djangoproject.com/download/1.3/tarball/|Django1.3]] [[http://theory.cpe.ku.ac.th/~jittat/204223/Django-1.3.tar.gz|mirror at ku]]
* [[204223-52|เนื้อหาจากวิชา practicum ปีการศึกษา 2552]]
===== โปรแกรมหมู่เช้า =====
* [[01204223-54-ex-django-code|โปรแกรมของหมู่เช้า]]
===== โปรแกรมหมู่บ่าย =====
แก้ ''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 ====
List of events
{% for e in events %}
{{ e.title }} - {{ e.place }}
{% for c in e.comment_set.all %}
- {{ c.body }}
{% endfor %}
{% endfor %}
==== events/admin.py ====
from models import Event
from django.contrib import admin
admin.site.register(Event)