I am trying to ajaxify my comment form so that it can be submitted without refreshing the page. I have a Comment model which has a ForeignKey to the Post model:
class Comment(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
body = models.TextField(max_length=500)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
content = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='posts')
Here is my template:
{% for post in posts %}
...
<div id="comList"">
{% if post.comment_set.all %}
{% for c in post.comment_set.all %}
<p>{{ c.body }}</p>
{% endfor %}
{% endif %}
</div>
<form id="addComForm" action="{% url 'posts:comment' %}" method="post">
{% csrf_token %}
<input type="hidden" name="post_id" value={{ post.id }}>
{{ c_form }}
<button id="addComBtn" type="submit" name="submit_c_form">Send</button>
</form>
{% endfor %}
<script>
$(document).ready(function() {
$('#addComBtn').click(function() {
var serializedData = $('#addComForm').serialize();
const url = $('#addComForm').attr('action')
$.ajax({
url: url,
data: serializedData,
type: 'POST',
success: function(response) {
$('#comList').append('<p>' + response.c.body + '</p>')
},
error: function(error) {
console.log(error)
}
})
});
});
</script>
Here is my view:
def comment_view(request):
profile = Profile.objects.get(user=request.user)
if 'submit_c_form' in request.POST:
c_form = CommentModelForm(request.POST)
if c_form.is_valid():
instance = c_form.save(commit=False)
instance.user = profile
instance.post = Post.objects.get(id=request.POST.get('post_id'))
instance.save()
return JsonResponse({'comment': model_to_dict(instance)}, status=200)
return redirect('posts:index')
And for reference, my form and relevant url:
class CommentModelForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
path('comment/', comment_view, name='comment'),
Currently on submit I am getting Uncaught TypeError: response.c is undefined
in the console, so I think the issue lies within my JsonResponse in the view. Any help received on this would be much appreciated