views.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from django.shortcuts import render, get_object_or_404
  2. from models import Post, Comment
  3. from forms import CommentForm
  4. from django.http import HttpResponseRedirect
  5. from django.core.urlresolvers import reverse
  6. from markdown import markdown
  7. # Create your views here.
  8. # change this to False and there will be no comment section
  9. COMMENTS_ALLOWED = True
  10. def index(request):
  11. '''
  12. List all blog posts.
  13. '''
  14. post_list = Post.objects.all().order_by('last_edited').reverse()
  15. context = {
  16. 'title': "Welcome",
  17. 'post_list': post_list,
  18. }
  19. return render(request, 'index.html', context)
  20. def detail(request, token):
  21. '''
  22. View a single blog post by its ID or post a comment if request is POST.
  23. token should be an integer.
  24. '''
  25. if request.method == "POST": # no GET allowed.
  26. p = get_object_or_404(Post, id=token)
  27. form = CommentForm(request.POST)
  28. if form.is_valid():
  29. # look around cleaned_data
  30. c = Comment(
  31. author=form.cleaned_data['author'],
  32. website=form.cleaned_data['website'],
  33. content=form.cleaned_data['content'],
  34. post=p,
  35. )
  36. c.save()
  37. return HttpResponseRedirect(reverse('detail', args=(token)))
  38. else:
  39. context = {
  40. 'title': post.title,
  41. 'post': post,
  42. 'content': content,
  43. 'comments': comments,
  44. 'commenting': COMMENTS_ALLOWED,
  45. 'form': form,
  46. 'error': "There were errors filling out the form.",
  47. }
  48. return render(request, 'detail.html', context)
  49. else: # GET
  50. post = get_object_or_404(Post,id=token)
  51. comments = Comment.objects.filter(post__id=token)
  52. content = markdown(post.content)
  53. form = CommentForm()
  54. context = {
  55. 'title': post.title,
  56. 'post': post,
  57. 'content': content,
  58. 'comments': comments,
  59. 'commenting': COMMENTS_ALLOWED,
  60. 'form': form,
  61. }
  62. return render(request, 'detail.html', context)