1👍
You can pass that instance of the Comment
model which you’d like to update in CommetForm
. In the get_form_kwargs()
method, you can add the instance
keyword argument to the form kwargs with the instance of the Comment model to update. Then, the CommentForm
will be pre-populated with the data from that instance while displaying in frontend so:
class CommentUpdate(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView):
model = Comment
template_name = 'blog/post_detail.html'
form_class = CommentForm
def get_success_url(self):
post = Post.objects.get(pk=self.object.post.pk)
messages.info(self.request, 'Comment updated')
return post.get_absolute_url()
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['instance'] = self.get_object()
return kwargs
def test_func(self):
comment = self.get_object()
if self.request.user == comment.author:
return True
return False
Source:stackexchange.com