===== โปรแกรม =====
==== 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 ====
List of events
{% for e in events %}
{{ e }} - {{ e.place }}
{% for comment in e.comment_set.all %}
- {{ comment }}
{% endfor %}
{% endfor %}
==== events/admin.py ====
from models import Event
from django.contrib import admin
admin.site.register(Event)