Django Ajax views.py cannot get the Object ID and returns 404 instead

Viewed 76

Hi I am trying to ajaxify my comment function of my blog app in Django. Right now the code works fine except one part: I am not able to transmit the Object ID I want to access to my views.py file. When I hardcode the Object ID everything works fine.

views.py file: (When I replace pk=request.POST.get('post_id') with the actual obj ID everything works!)

@login_required
def comment_create(request):
    post = get_object_or_404(Post, pk=request.POST.get('post_id'))
    user = get_object_or_404(User, username=request.user)
    comment_form = CommentForm()

    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.author = user
            new_comment.save()
    else:
        comment_form = CommentForm()

    if request.is_ajax():
        html = render_to_string('feed/comment_section.html', {'post': post}, request=request)
        return JsonResponse({'form': html})

The comment form in my html:

<div>
    <form class="comment-form" action="{% url 'comment-create' %}" method="POST">
        <div class="row">
        {{ comment_form.as_p }}
        {% csrf_token %}
        <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-info">Submit</button>
        </div>
    </form>
</div>

My jQuery event handler:

$(document).on('submit', '.comment-form', function(event){
                event.preventDefault();
                console.log($(this).serialize());
                $.ajax({
                    type: 'POST',
                    url: $(this).attr('action'),
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(response) {
                        $('#comment-section').html(response['form']);
                        console.log($('#comment-section').html(response['form']));
                    },
                    error: function(rs, e){
                        console.log($(rs.responseText));
                    },
                });
            });

I tried various things but I do not know how I can make sure the post_id gets handed over to my comment_create() function..

1 Answers

The problem is that your form don't have a field with name post_id. You've added name="post_id" value="{{ post.id }}" to your submit button - but it won't be considered as a form field by your html form.

Solution is, as I've mentioned in my comment, adding a hidden input element as shown below:

<div>
    <form class="comment-form" action="{% url 'comment-create' %}" method="POST">
        <div class="row">
        {{ comment_form.as_p }}
        {% csrf_token %}
        <input type="hidden" name="post_id" value="{{ post.id }}">
        <button type="submit" class="btn btn-info">Submit</button>
        </div>
    </form>
</div>

This way your html form knows it has to submit the field post_id. Hope it helps

Related