|
1 | | -# from django.shortcuts import render |
| 1 | +from django.shortcuts import render |
2 | 2 |
|
3 | | -# Create your views here. |
| 3 | +from blog.forms import CommentForm |
| 4 | +from blog.models import Post, Comment |
| 5 | + |
| 6 | + |
| 7 | +def blog_index(request): |
| 8 | + posts = Post.objects.all().order_by("-created_on") |
| 9 | + context = {"posts": posts} |
| 10 | + return render(request, "blog_index.html", context) |
| 11 | + |
| 12 | + |
| 13 | +def blog_category(request, category): |
| 14 | + posts = Post.objects.filter(categories__name__contains=category).order_by( |
| 15 | + "-created_on" |
| 16 | + ) |
| 17 | + context = {"category": category, "posts": posts} |
| 18 | + return render(request, "blog_category.html", context) |
| 19 | + |
| 20 | + |
| 21 | +def blog_detail(request, pk): |
| 22 | + post = Post.objects.get(pk=pk) |
| 23 | + comments = Comment.objects.filter(post=post) |
| 24 | + |
| 25 | + form = CommentForm() |
| 26 | + if request.method == "POST": |
| 27 | + form = CommentForm(request.POST) |
| 28 | + if form.is_valid(): |
| 29 | + comment = Comment( |
| 30 | + author=form.cleaned_data["author"], |
| 31 | + body=form.cleaned_data["body"], |
| 32 | + post=post, |
| 33 | + ) |
| 34 | + comment.save() |
| 35 | + |
| 36 | + context = {"post": post, "comments": comments, "form": form} |
| 37 | + return render(request, "blog_detail.html", context) |
0 commit comments