0

I tried to add comments with the post and it raise this error, and I supmit my comment using ajax but it seems the problem coming from the view but I couldn't figure out what exactly the problem

My add comments View

@login_required
def add_comment_post(request):
comment_form = PostCommentForm(request.POST)
            if comment_form.is_valid():
                user_comment = comment_form.save(commit=False)
                user_comment.author = request.user
                user_comment.save()

                result = comment_form.cleaned_data.get('content')
                user = request.user.username
                return JsonResponse({'result': result, 'user': user})

My comment Model

class PostCommentIDF(MPTTModel):

    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com')
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children')
    author = models.ForeignKey(Account, on_delete=models.CASCADE)
    content = models.TextField()
    publish = models.DateTimeField(auto_now_add=True)
    status = models.BooleanField(default=True)
    likes = models.ManyToManyField(Account, blank=True, related_name='pos_com')

    class MPTTMeta:
        order_insertion_by = ['-publish']

    def __str__(self):
        return f'{self.author}---{self.content[:15]}'

My form for the comments

class PostCommentForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

class Meta:
    model = PostCommentIDF
    fields = {'post', 'content'}
    widgets = {
        'content': forms.Textarea(attrs={'class': 'rounded-0  form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True'})
    }
def save(self, *args, **kwargs):
    PostCommentIDF.objects.rebuild()
    return super(PostCommentForm, self).save(*args, **kwargs)

the comments form in the template

                  <form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;">
                      {% load mptt_tags %}
                        {% csrf_token %}
                                    <select class="d-none" name="video" id="id_video">
                                        <option value="{{ video.id }}" selected="{{ video.id }}"></option>
                                    </select>
                                          <div class="d-flex">
                                    <label class="small font-weight-bold">{{ comments.parent.label }}</label>
                                    {{ comment_form.parent }}

                                    {{comments.content}}
                    
                                <button value="Postcommentform" id="Postnewcomment" type="submit"  style="color: white; border-radius: 0;" class="d-flex justify-content-end btn btn-primary">Post</button>
                              </div>
                  </form>
Ahmed
  • 280
  • 1
  • 12
  • 3
    your comment form is not valid `if comment_form.is_valid()` is False, and as such the view returns None. – Ben May 15 '21 at 06:32
  • Thank you for your answer, How I can let it valid, I pass the content to the template, I need to pass any other faild from the comment model – Ahmed May 15 '21 at 06:43
  • As far as I know the is_valid can return false without an exception raised if the form is empty meaning request.POST contains nothing to fill the form with. – Razenstein May 15 '21 at 06:53
  • Is this problem happen from the template, because I fill the form after I supmit it this problem raise – Ahmed May 15 '21 at 07:00
  • Try a print(request.POST) to see what is in it before the "comment_form=..." – Razenstein May 15 '21 at 08:32
  • As you are submitting the form with js the error might be in your ajax code. – Razenstein May 15 '21 at 08:42
  • I maybe started figure out the problem my problem in ` – Ahmed May 15 '21 at 08:51
  • 1
    You can view the errors you are getting by printing out the errors which should point you to the erroring fields: `print(comment_form.errors)` :: https://docs.djangoproject.com/en/3.2/ref/forms/api/#django.forms.Form.errors – Ben May 17 '21 at 18:07

1 Answers1

0

When form is not valid your the codes under your if statement will not execute so your function will return None instead of an HttpResponse.
You should handle it with in a esle statement for example:

@login_required
def add_comment_post(request):
    comment_form = PostCommentForm(request.POST)
    if comment_form.is_valid():
        user_comment = comment_form.save(commit=False)
        user_comment.author = request.user
        user_comment.save()

        result = comment_form.cleaned_data.get('content')
        user = request.user.username
        return JsonResponse({'result': result, 'user': user})
    else:
        return JsonResponse({'result': "form is not valid"})
Mojtaba Arezoomand
  • 2,140
  • 8
  • 23