views.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from django.shortcuts import render, get_object_or_404, redirect
  2. from django.utils import timezone
  3. from .models import Post
  4. from .forms import PostForm
  5. # Create your views here.
  6. def post_list(request):
  7. posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
  8. return render(request, 'blog/post_list.html', {'posts':posts})
  9. def post_detail(request, pk):
  10. # Failsafe version of:
  11. # post = Post.object.get(pk=pk)
  12. post = get_object_or_404(Post, pk=pk)
  13. return render(request, 'blog/post_detail.html', {'post':post})
  14. def post_new(request):
  15. if request.method == "POST":
  16. # filled post details and submited
  17. form = PostForm(request.POST)
  18. if form.is_valid():
  19. post = form.save(commit=False)
  20. post.author = request.user
  21. post.published_date = timezone.now()
  22. post.save()
  23. return redirect('post_detail', pk=post.pk)
  24. else:
  25. # Just opened new_post page
  26. form = PostForm()
  27. return render(request, 'blog/post_edit.html', {'form':form})
  28. def post_edit(request, pk):
  29. post = get_object_or_404(Post, pk=pk)
  30. if request.method == "POST":
  31. form = PostForm(request.POST, instance=post)
  32. if form.is_valid():
  33. post = form.save(commit=False)
  34. post.author = request.user
  35. post.published_date = timezone.now()
  36. post.save()
  37. return redirect('post_detail', pk=post.pk)
  38. else:
  39. form = PostForm(instance=post)
  40. return render(request, 'blog/post_edit.html', {'form':form})