Source

lindyjam / blog / views.py

Full commit
from lindyjam.blog.models import Entry, Comment
from django.template import Context, loader
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from markdown import markdown
import simplejson as json

ENTRIES_PER_PAGE = 3
COMMENT_MESSAGE = """<p class="success">Thanks for speaking up!</p>"""

def index(request, page=0):
    page = int(page)
    start_index = page * ENTRIES_PER_PAGE
    end_index = start_index + ENTRIES_PER_PAGE
    entries = Entry.objects.all().order_by('-pub_date')
    entries = entries.filter(published=True)[start_index:end_index]
    return render_to_response('blog/index.html', 
        { 'entries': entries,
          'older_page': page+1 if end_index < Entry.objects.count() else None,
          'newer_page': page-1 if page != 0 else None },
          context_instance=RequestContext(request)  )

def entry(request, year, month, day, slug):
    entry = get_object_or_404(Entry, 
        pub_date__year=year, pub_date__month=month, pub_date__day=day, 
        slug=slug)
    return render_to_response('blog/entry.html', { 'entry': entry, },
                              context_instance=RequestContext(request) )

def comment(request):
    errors = []
    status = 0
    fields = request.POST
    
    if fields['name'] == '':
        errors.append("You have to give a name!")
    if fields['body'] == '':
        errors.append("You have to say something!")
    
    if len(errors) > 0:
        status = -1
        error_message = '\n'.join(['<p class="error">%s</p>' % (e,) 
                                   for e in errors])
        return HttpResponse(json.dumps( { 'status': status,
                                          'data': error_message }))
                                          
    entry = Entry.objects.get(pk=fields['entry_id'])
    
    new_comment = Comment(name=fields['name'], 
                          body=fields['body'],
                          entry=entry)
    new_comment.save()
    
    t = loader.get_template('blog/single_comment.html')
    c = Context({ 'comment': new_comment, })
    
    return HttpResponse(json.dumps( 
        { 'status': status,
          'data': COMMENT_MESSAGE,
          'new_comment': t.render(c) }))