Plankton_Detector/PlanktonDetector/Community/views.py

52 lines
1.5 KiB
Python
Raw Normal View History

from typing import Any
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.shortcuts import redirect, render
2023-12-13 02:11:29 +01:00
from django.views.generic import ListView, DetailView
from django.views.generic.edit import FormView, FormMixin
2023-12-13 02:11:29 +01:00
from .models import Post, Comment
from .froms import PostForm, CommentForm
2023-12-13 02:11:29 +01:00
class ListPosts(ListView):
model = Post
template_name = "list_posts.html"
2024-01-07 01:10:31 +01:00
paginate_by = 4
def get_queryset(self) -> QuerySet[Any]:
queryset = Post.objects.all().order_by("-date_pub")
return queryset
2023-12-13 02:11:29 +01:00
class PostDetails(DetailView, FormMixin):
2023-12-13 02:11:29 +01:00
model = Post
2023-12-19 17:33:46 +01:00
template_name = "post_details.html"
form_class = CommentForm
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form) -> HttpResponse:
post = self.get_object()
new_comment = form.save(commit=False)
new_comment.author = self.request.user
new_comment.post = post
new_comment.save()
return redirect("post-details", pk=post.id)
class AddPost(FormView):
template_name = "add_post.html"
form_class = PostForm
def form_valid(self, form) -> HttpResponse:
new_post = form.save(commit=False)
new_post.author = self.request.user
new_post.save()
return redirect("post-details", pk=new_post.id)