Table of Contents

โปรแกรม

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'^$', 'myevents.events.views.list'),
    url(r'^post_comment/(\d+)/$',
        'myevents.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
from django.views.decorators.csrf import csrf_exempt
 
def list(request):
  events = Event.objects.all()
  return render_to_response("list.html",
                            { 'events': events })
 
@csrf_exempt
def create_comment(request,event_id):
  event = Event.objects.get(pk=event_id)
  c = Comment(body=request.POST['body'], event=event)
  c.save()
  return redirect('/')

events/templates/list.html

<html>
<body>
<h1>List of events</h1>
{% for e in events %}
  <b>{{ e }}</b> - <small>{{ e.place }}</small><br />
  <ul>
    {% for comment in e.comment_set.all %}
      <li>{{ comment }}</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)