1👍
✅
You use an UpdateView
, hence it aims to update a comment with that id, so if there is a coincidence with the blog id, and a comment id, that comment is modified, which is likely not a good idea.
You can use a CreateView
that uses the pk
as blog_id
:
from django.views.generic import CreateView
class CommentCreateView(LoginRequiredMixin, CreateView):
model = BlogComment
form_class = CommentUpdateForm
template_name = 'talesoflnk/blog_comment_update_form.html'
def get_context_data(self, **kwargs):
return super().get_context_data(
**kwargs, blog=get_object_or_404(Blog, pk=self.kwargs['pk'])
)
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.blog_id = self.kwargs['pk']
return super().form_valid(form)
def get_success_url(self):
return reverse('blog-detail', kwargs={'pk': self.kwargs['pk']})
Note: Since PEP-3135 [pep], you don’t need to call
super(…)
with parameters if the first parameter is the class in which you define the method, and the second is the first parameter (usuallyself
) of the function.
Source:stackexchange.com