I wanted to add a comment section but i got a post() missing 1 required positional argument: 'post_id' ` error
class PostDetailView(DetailView):
model = Post
template_name = "post_detail.html"
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
post = get_object_or_404(Post, id=self.kwargs['pk'])
comments = Comment.objects.filter(post=post).order_by('-id')
total_likes = post.total_likes()
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
comment_form = CommentForm()
context["total_likes"] = total_likes
context["liked"] = liked
context["comments"] = comments
context["comment_form"] = comment_form
return context
class PostCommentCreateView(CreateView):
model = Comment
fields = ['content']
def get(self, request, post_id, *args, **kwargs):
raise Http404
def post(self, request, post_id, *args, **kwargs):
self.post = Post.objects.get_or_404(id=post_id)
self.user = request.user
super().post(request, *args, **kwargs)
def form_valid(self, form):
form.instance.post = self.post
form.instance.user = self.user
return super(PostCommentCreateView, self).form_valid(form)
<form action={% url 'post-comment' Post.id %} method="post" class="comment-form" action=".">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
<input type="submit" value="Submit" class="btn btn-outline-success">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-success" disabled> You must be Logged in to Comment
{% endif %}
</form>
Resolved using this code, thank you ``` class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content', ] success_url = reverse_lazy('score:post-detail') def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = form.save() post.save() print(args, kwargs, request.POST) return redirect('score:post-detail', slug=kwargs['slug']) ```