'Django Blog - edit/delete user comments functions help needed pls
I am quite new to software development and quite new to django and python. I am currently working on a project to develop blog, which needs to have functions for users to edit and delete their own comments.
Whilst I have developed the blog, I am struggling with getting the functions correctly coded and wired up to URLS file.
I have added icons below user comments to either delete or edit their comments.
My question is what is the correct code for creating functions in views file and also how can i correctly wire it up to URL file. I am not sure if I am missing any packages to get the edit/delete functionality developed.
I have enclosed details of my model, views and urls files. Any guidance/support will be highly appreciated.
Models file
from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
STATUS = ((0, "Draft"), (1, "Published"))
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
featured_image = CloudinaryField('image', default='placeholder')
excerpt = models.TextField(blank=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
likes = models.ManyToManyField(User, related_name='blog_likes', blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def number_of_likes(self):
return self.likes.count()
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
class Meta:
ordering = ['-created_on']
def __str__(self):
return f"Comment {self.body} by {self.name}"
Views file
from django.shortcuts import render, get_object_or_404, reverse
from django.views import generic, View
from django.http import HttpResponseRedirect
from .models import Post
from .forms import CommentForm
class PostList(generic.ListView):
model = Post
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
paginate_by = 4
class PostDetail(View):
def get(self, request, slug, *args, **kwargs):
queryset = Post.objects.filter(status=1)
post = get_object_or_404(queryset, slug=slug)
comments = post.comments.filter(approved=True).order_by("-created_on")
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
return render(
request,
"post_detail.html",
{
"post": post,
"comments": comments,
"commented": False,
"liked": liked,
"comment_form": CommentForm()
},
)
def post(self, request, slug, *args, **kwargs):
queryset = Post.objects.filter(status=1)
post = get_object_or_404(queryset, slug=slug)
comments = post.comments.filter(approved=True).order_by("-created_on")
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.email = request.user.email
comment_form.instance.name = request.user.username
comment = comment_form.save(commit=False)
comment.post = post
comment.save()
else:
comment_form = CommentForm()
return render(
request,
"post_detail.html",
{
"post": post,
"comments": comments,
"commented": True,
"liked": liked,
"comment_form": CommentForm()
},
)
class PostLike(View):
def post(self, request, slug):
post = get_object_or_404(Post, slug=slug)
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[slug]))
Urls file
from . import views
from django.urls import path
urlpatterns = [
path("", views.PostList.as_view(), name="home"),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'),
]
Solution 1:[1]
As you are using class based views, there are generic views already set up for Updating and Deleting: See the docs https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-editing/
Your icons can simply be links to those views, and the rest is handled for you. You don't need to add complexity to your PostDetails view.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SamSparx |
