我在Django Ajax中实现了Like功能,但是当我刷新页面时,我推送的Like消失了。 为什么?
我以为
body:
post_pk={{ post.pk }}`有问题,并查看了它,但无法弄清楚。
模型.py
from django.db import models
from accounts.models import CustomUser
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
ordering = ["-created_at"]
class Like(models.Model):
user_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
target = models.ForeignKey(Post, on_delete=models.CASCADE)
views.py
class DeletePost(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
template_name = 'delete.html'
success_url = reverse_lazy('home')
def test_func(self, **kwargs):
pk = self.kwargs['pk']
post = Post.objects.get(pk=pk)
return (post.user == self.request.user)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
like_count = self.object.like_set.count()
context['like_count'] = like_count
if self.object.like_set.filter(user_id=self.request.user).exists():
context['is_user_liked'] = True
else:
context['is_user_liked'] = False
return context
def like(request):
post_pk = request.POST.get('post_pk')
context = {'user_id': f'{ request.user }'}
article = get_object_or_404(Post, pk=post_pk)
like = Like.objects.filter(target=article, user_id=request.user)
if like.exists():
like.delete()
context['method'] = 'delete'
else:
like.create(target=article, user_id=request.user)
context['method'] = 'create'
context['like_count'] = article.like_set.count()
return JsonResponse(context)
detail.html
{% extends "base.html" %}
{% load static %}
{% block title %}{% endblock %}
{% block content %}
<div class="container">
<div class="alert alert-success" role="alert">
<p>タイトル:{{object.title}}</p>
<p>投稿者:{{object.user}}</p>
<p>コメント:{{object.content|safe}}</p>
<div class="card-header">
{% if is_user_liked %}
<button type="button" id="ajax-like" style="border:none;background:none">
<!-- すでにいいねしている時はfasクラス -->
<i class="fas fa-heart text-danger" id="like-icon"></i>
</button>
{% else %}
<button type="button" id="ajax-like" style="border:none;background:none">
<!-- いいねしていないときはfarクラス -->
<i class="far fa-heart text-danger" id="like-icon"></i>
</button>
{% endif %}
<!-- いいねの数 -->
<span id="like-count">{{ like_count }}</span>
<span>いいね</span>
</div>
{% if object.user == request.user %}
<a href="{% url 'myapp:update' pk=object.pk %}" class="btn btn-primary ms-3" tabindex="-1" role="button" aria-disabled="true">編集</a>
<a href="{% url 'myapp:delete' pk=object.pk %}" class="btn btn-danger ms-3" tabindex="-1" role="button" aria-disabled="true">削除</a>
{% endif %}
</div>
</div>
<script type="text/javascript">
// いいねボタンが押された時
document.getElementById('ajax-like').addEventListener('click', e => {
e.preventDefault();
const url = '{% url "myapp:like" %}';
fetch(url, {
method: 'POST',
body: `post_pk={{ post.pk }}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'X-CSRFToken': '{{ csrf_token }}',
},
}).then(response => {
return response.json();
}).then(response => {
// いいね数を書き換える
const counter = document.getElementById('like-count')
counter.textContent = response.like_count
const icon = document.getElementById('like-icon')
// いいねした時はハートを塗る
if (response.method == 'create') {
icon.classList.remove('far')
icon.classList.add('fas')
icon.id = 'like-icon'
} else {
icon.classList.remove('fas')
icon.classList.add('far')
icon.id = 'like-icon'
}
}).catch(error => {
console.log(error);
});
});
</script>
{% endblock %}
您可以尝试将
like.create(target=article, user_id=request.user)
更改为article.like_set.create(user_id=request.user)
吗?
此外,响应中的值是否正确?你可以打开 Django Admin 并检查是否创建了新的类似对象?