1👍
✅
Error is comming from this line url: "{% url 'save-post' post.id %}",
here you don’t have access to your post
object because it’s not inside loop you can solve your problem like this you don’t have create form and set your button type to submit if you’re using ajax request change your code like this
<button class="savebutton" type="button" name="post_id" title="Save Post" id="save" onclick="savePost(event)" value="{{ post.id }}" data-url="{% url 'save-post' post.id %}">
<i class="fas fa-bookmark"></i> Save Post
</button>
and you ajax call will look like this
<script>
function savePost(event){
var url = event.target.getAttribute("data-url");
$.ajax({
type: 'POST',
url: url,
data: {
postid: event.target.getAttribute('value'),
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
alert('Post saved!')
},
error: function () {
alert('Error!')
}
});
}
</script>
0👍
in the Ajaxsave function you didnt specifiy the pk you should link it to one of the objects then start making the post so the view couldn’t return back the reverse query you are trying to load , the best practices for using AJAX request is by using Django-Rest-Framework so it handle all the requests.
def AjaxSave(request, pk):
pk = module.objects.get(pk=pk)
if request.method == "POST":
# or you can get the pk here if you want without parsing to int
id = int(request.POST.get('postid'))
result = post.saves.count()
post = get_object_or_404(Post, id=id)
if post.saves.filter(id=request.user.id).exists():
post.saves.remove(request.user)
post.save()
else:
post.saves.add(request.user)
post.save()
return JsonResponse({'result': result, })
- [Answered ]-Django : Read multiple file from html form
- [Answered ]-Exporting a development django application to production
Source:stackexchange.com