1

I'm trying make a comment section for my Q&A project.I made the model for comment , the form part in question_detail.html an , also the QuestionCommentForm() in form.py .

model.py

class QuestionComment(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    question = 
    models.ForeignKey(Question,on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add= True)
    body = models.CharField(max_length=200, null= True , 
    blank = True, default ='')
    def __str__(self):
    return str(self.body)

forms.py

          {%if c_form%}
    <form method="POST" action= "{% usl 'blog:question-commet' question.id  >{% csrf_token %}
    {{c_form.media}}
    {{ c_form.as_p}}
      <button type = "submit" , name = "question_id", value = "{{question.pk}}", class ="btn btn-secondary btn-sm">submit comment</button>

views.py

@api_view(['POST','GET'])
def question_comment(request, *args, **kwargs):
    form = QuestionCommentForm()
     print('finction comment started'*20)
     if request.method == 'POST':
        c_form = QuestionCommentForm(request.POST)
        if c_form.is_valid():        
            new_comment = c_form.save(commit=False)
            new_comment.refresh_from_db()
            c_form.instance.user = request.user
            question = Question.objects.get(id = request.POST.get('question_id')

            new_comment.question = question
            new_comment.bldy =c_form.cleaned_data.get('body')
            new_comment.save()
    context['c_form'] = c_form
    return render(request, 'blog/question_detail.html',context)

class QuestionDetail(DetailView):
    template_name = 'blog/question_detail.html'
    model = Question
    context_object_name = 'question'
    count_hit = True
    def get_queryset(self):
        return Question.objects.filter(id = self.kwargs['pk'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        c_form = QuestionCommentForm()
        context = super(QuestionDetail,self).get_context_data(**kwargs)
        self.obj= get_object_or_404(Question, id = self.kwargs['pk'])
        self.object.save()
        self.object.refresh_from_db()
        answers = Answer.objects.filter (question_id = self.obj.id).order_by('-created_date')
        liked =self.obj.like.filter(id =self.request.user.id).exists()
        print('liked in class question not checked still' *10)
        comments= QuestionComment.objects.filter(question = self.kwargs['pk'])
        context['comments']= comments
        context["answers"]=answers
        context["liked "] = liked
        context['c_form'] = c_form
        return context

    def post(request, *args, **kwargs):
        print('post started'*100)
        c_form = QuestionCommentForm()
        c_form = QuestionCommentForm(request.POST)
        if c_form.is_valid():        
            new_comment = c_form.save(commit=False)
            new_comment.refresh_from_db()
            new_comment.user = request.user
            new_comment.question = c_form.cleaned_data.get('question_id')
            new_comment.bldy =c_form.cleaned_data.get('body')
            new_comment.save()
            context['c_form'] = c_form
        else:
            c_form= QuestionCommentForm()
        return render(request, 'blog/question_detail.html',context)
    

url.py

...
path('question-comment/<int:pk>/', question_comment, name = 'question-comment'),

]

in my view, first I tried to use a another function to handle the comment, got no result and made a def post() in the class QuestionDetial() , and still the form shows up but when I type something and hit the button , it refresh the page and nothing saves . I have already saved a comment using admin and it appears in the question-detail page. used print to find the bug, but it seems the post() in class and the question_comment() not being recall. searched a lot but no answer. (BTW I get no error except the NoReverseMatch that I fixed)

1
  • Thank you in advance Commented Jan 2, 2021 at 15:23

2 Answers 2

1

You never save the model object (not by the form, nor by the view). Furthermore the name of the method is 'POST', not 'Post':

@api_view(['POST','GET'])
def question_comment(request, *args, **kwargs):
    form = QuestionCommentForm()
    print('finction comment started'*20)
    if request.method == 'POST':
        c_form = QuestionCommentForm(request.POST)
        if c_form.is_valid():        
            c_form.instance.user = request.user
            c_form.save()
    context = {'c_form': c_form }
    return render(request, 'blog/question_detail.html',context)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank's but I had done that (.save() in the class) , and I changed it as you said now but still not saving , my print() functions are not working both in question_comment() and in post method in class QuestionComment .
@RoohollahMozaffari: no, since you still did not alter the request.method == 'POST' check, so the if logic is never performed. It would also error, since request.Post does not exist either.
1

ok , the problem was that I had two form-tags in question_detail template and buy adding comment form in the end of the template had 3 , but the problem was when I pressed the submit comment button the terminal showed this message

"POST /create-like/blog/answer/18/ HTTP/1.1" 302 0

which was the form I had made for like function .(while my url was question-comment) I accidentally forgot to close the like-form tag in template. so all I needed was putting a

 </form>

after the form block . thank's Willem Van Onsem. it solved my post method error. and these were very helpful

Proper way to handle multiple forms on one page in Django

How can I build multiple submit buttons django form?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.