我正在Web应用程序中实现类似的功能。这个想法很简单,可以在主页上列出帖子(Blog)的数量,并为每个帖子(Blog)添加一个Like按钮。当我用普通的方法构建它时,它工作得很好
<form action='{% url target %}' method='POST'>
但是,当我用AJAX调用实现这个功能时,它只允许我一次喜欢或不喜欢某个特定的帖子(blog),也就是说,我第一次喜欢某个帖子时,它可以工作,当我不喜欢同一个帖子时,它也可以工作,但当我再次喜欢这个帖子时,它会抛出一个django.db.utils.OperationalError: database is locked
而且,当我喜欢同一个帖子多次(4到5次)的时候,它会以一种奇怪的方式回应。我在喜欢和不喜欢的职位循环。你知道吗
就像_节.html你知道吗
<form id="like-form{{ post.id }}">
{% csrf_token %}
<button type="submit" id="{{ post.id }}btn" name="like" value="{{ post.id }}" class="btn upvote">Like</button>
<script type="text/javascript">
{% for like in post.likes.all %}
{% if like != user %}
dislikingPost("{{ post.id }}btn");
{% else %}
likingPost("{{ post.id }}btn");
{% endif %}
{% endfor %}
$(document).ready(function(event){
$(document).on('click', '#{{ post.id }}btn', function(event){
event.preventDefault();
pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like_post" %}',
data: {
'id': pk,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success:function(response){
$('#like-form{{ post.id }}').html(response['form'])
// $('#{{ post.id }}btn').style.color = 'green';
}, error: function(er, e){
console.log(er.responseText);
}
});
});
});
</script>
</form>
你知道吗视图.py地址:
def like_post(request):
all_posts = Posts.objects.all()
print("Insisde Like Post")
print('ID coming from form is', request.POST.get('id'))
post = get_object_or_404(Posts, id=request.POST.get('id')) # for AJAX call
context = {
'all_posts': all_posts,
'post': post
}
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user) # Liking The Post
print("DisLiking the post")
else:
post.likes.add(request.user)
print("Liking the post")
if request.is_ajax():
print('Hey its an AJAX calls') # TEsting AJAX request
html = render_to_string('like_section.html', context, request=request)
return JsonResponse({'form': html})
注: 1我是AJAX的初学者。 2我知道SQLite不能处理多余的调用,但是为什么它以前在没有AJAX调用的情况下工作。 三。我不提供型号.py和完整的主页模板,我不认为他们是必需的。你知道吗
问题不在于Django代码。这是一个ajax调用,它在一个按钮上触发了数据库多次。你知道吗
在ajax调用中在
event.preventDefault();
下面添加event.stopImmediatePropagation();
非常有效相关问题 更多 >
编程相关推荐