Reputation: 3
I currently use a function based view to let users write comments on posts, but I'm trying to convert it to class based views
Function views.py
def comment(request, pk):
form = CommentForm(request.POST)
# Post instance
post_instance = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
if form.is_valid:
obj = form.save(commit=False)
obj.commenter = request.user
obj.post = post_instance
obj.save()
return redirect('/')
else:
messages.error(request, 'Comment Failed')
return render(request, 'comment.html', {'form': form})
Class views.py
class CommentView(FormView):
template_name = 'comment.html'
form_class = CommentForm
success_url = '/'
def get_object(self):
pk = self.kwargs.get('pk')
post_instance = get_object_or_404(Post, pk=pk)
return post_instance
def form_valid(self, form):
obj = form.save(commit=False)
obj.commenter = self.request.user
obj.post = post_instance
obj.save()
return super().form_valid(form)
I'm trying to implement the same logic for saving the comment but I get the error: name 'post_instance' is not defined
get_object() is returning the 'post_instance' variable but I can't access it. Could you guys show me where I'm doing a mistake, thanks in advance!
Upvotes: 0
Views: 1459
Reputation: 493
You can try:
class CommentView(FormView):
template_name = 'comment.html'
form_class = CommentForm
success_url = '/'
def get_object(self):
pk = self.kwargs.get('pk')
post_instance = get_object_or_404(Post, pk=pk)
return post_instance
def form_valid(self, form):
obj = form.save(commit=False)
obj.commenter = self.request.user
obj.post = self.get_object()
obj.save()
return super().form_valid(form)
Upvotes: 1