Plankton_Detector/PlanktonDetector/Community/views.py

78 lines
2.2 KiB
Python
Raw Normal View History

from typing import Any
from django.db.models.query import QuerySet
2024-01-14 23:12:35 +01:00
from django.forms.models import BaseModelForm
from django.http import HttpResponse
from django.shortcuts import redirect, render
2024-01-14 23:12:35 +01:00
from django.urls import reverse_lazy
from django.views import View
2023-12-13 02:11:29 +01:00
from django.views.generic import ListView, DetailView
2024-01-14 23:12:35 +01:00
from django.views.generic.edit import FormView, FormMixin, UpdateView
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)
2024-01-14 23:12:35 +01:00
class UpdatePost(UpdateView):
model = Post
fields = ["title", "content"]
template_name = "add_post.html"
def form_valid(self, form: BaseModelForm) -> HttpResponse:
post = form.save()
return redirect("post-details", pk=post.id)
def delete_post(request, pk):
object = Post.objects.get(pk=pk)
object.delete()
return redirect("posts")
def delete_comment(request, pk):
object = Comment.objects.get(pk=pk)
post = object.post
object.delete()
return redirect("post-details", pk=post.id)