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..