usef
usef

Reputation: 73

django form always not valid

I'm using ajax to send data to my view, the goal is to post comments without refreshing the page

the problem is that the form always returns false when checking if valid or not, I cant find the problem hope you can help me

when i submit the form it return result:"" because the form is invalid

so I printed comment_form.errors and it looks like the data is empty

<ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li><li>question<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

my View

def question_detail(request, slug):

    question = get_object_or_404(Question, slug=slug)

    allcomments = question.comments.all()

    comment_form = CommentCreateForm()

    return render(request, 'question/question_detail.html', {'question': question, 'form': comment_form, 'comments': allcomments})

def add_comment(request):

    if request.is_ajax() and request.method == 'POST':
        comment_form = CommentCreateForm(data=request.POST)
        print(comment_form.is_valid())
        
        if comment_form.is_valid():
            print('hi')
            user_comment = comment_form.save(commit=False)
            result = comment_form.cleaned_data.get('content')
            user = request.user
            user_comment.author = user
            user_comment.save()
            return JsonResponse({'result': result, 'user': user.username})
        else:
            print('anything')
    return JsonResponse({"result": ''})

my template

                <form id="commentform" data-question="{{question.slug}}" class="commentform" method="POST">
                    <legend class="border-bottom fw-bold">Add a Comment</legend>
                    {% csrf_token %}

                    <select name="question" id="id_question" class="d-none">
                        <option value="{{question.id}}" selected="{{question.id}}"></option>
                    </select>
                    <label>{{form.parent.label}}</label>
                    {{form.parent}}

                    {{form.content}}
                    <button type="submit" value="commentform" id="newcomment"
                        class="newcomment btn btn-primary col-12 mt-1">Post</button>
                </form>

    $(document).on('click', '#newcomment',' #newcommentinner', function(e){
    e.preventDefault();

    let button = $(this).attr("value");
    // let slug = $('#commentform').attr("data-question") 
    let csrftoken = $('[name="csrfmiddlewaretoken"]').val();
    // let patch = "{% url 'question:question_detail' 0 %}".replace(0, slug)
    console.log($("#commentform").serialize())

    var placement = "commentform"
    if (button == "newcommentform") {
      var placement = "newcommentform"
    }
    $.ajax({
        type:'POST',
        url:"{% url 'question:add_comment' %}",
        data:{
            'data': $("#" + button).serialize(),
            'csrfmiddlewaretoken': csrftoken,
        },
        cache:false,
        success: function(json) {
            console.log(json)
        },
        error: function(xhr, errmsg, err){
        }
    })
});

Upvotes: 0

Views: 173

Answers (1)

Dimitris Kougioumtzis
Dimitris Kougioumtzis

Reputation: 2439

Not tested but will get a guide

def add_comment(request):
   if request.is_ajax() and request.method == 'POST':
     comment_form = CommentCreateForm(request.POST)
     print(comment_form)
     if comment_form.is_valid():
        user_comment = comment_form.save(commit=False)
        result = comment_form.cleaned_data.get('content')
        user = request.user
        user_comment.author = user
        user_comment.save()
        return JsonResponse({'result': result, 'user': user.username})
  return JsonResponse({"result": ''})

Upvotes: 1

Related Questions