喜欢/不喜欢帖子而无需刷新页面

时间:2020-07-24 21:31:45

标签: jquery json django django-models django-rest-framework

我一直在开发一个类似的系统,在该系统中,用户可以喜欢帖子,并且与该用户是否喜欢过帖子不同,该帖子与instagram非常相似。因此,在完成该系统的工作后,我意识到每次按下按钮都会重新加载页面,并且我不希望这种情况发生,经过一些调查,我得出的结论是可以使用json或jquery完成此操作,但是问题是我并没有真正之所以使用它,是因为我现在只专注于学习django。按下按钮后,如何使页面不刷新的代码?

models.py

class Post(models.Model):
    text = models.CharField(max_length=200)
    video = models.FileField(upload_to='clips', null=True, blank=True)
    user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
    liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
    updated = models.DateTimeField(auto_now=True)
    created =models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.text)

    def get_absolute_url(self):
        return reverse('comments', args=[self.pk])

LIKE_CHOICES = (
    ('Like', 'Like'),
    ('Unlike', 'Unlike'),
)

class Like(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10)

    def __str__(self):
        return str(self.post)

views.py

def like_post(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post_id)

        if user in post_obj.liked.all():
            post_obj.liked.remove(user)
        else:
            post_obj.liked.add(user)

        like, created = Like.objects.get_or_create(author=user, post_id=post_id)

        if not created:
            if like.value == 'Like':
                like.value == 'Unlike'
            else:
                like.value = 'Like'
        
        like.save()
    return redirect('home')

def home(request):
    contents = Post.objects.all()

    context = {
        "contents": contents,
    }
    print("nice2")
    return render(request, 'home.html', context)

home.html

<form action="{% url 'like-post' %}" method="POST">
  {% csrf_token %}
  <input type='hidden' name="post_id" value="{{ content.id }}">
  {% if user not in content.liked.all %}
    <button type="submit">Like</button>
  {% else %}
    <button type="submit">Unlike</button>
  {% endif %}
</form>
<strong>{{ content.liked.all.count }}</strong>

1 个答案:

答案 0 :(得分:0)

您可以为此使用AJAX请求。您可以阅读有关如何在django中使用AJAX的文档,例如因此,这是一个非常好的答案:https://stackoverflow.com/a/20307569/13290801

仅仅因为您专注于学习django并不意味着您可以忽略其他语言,因为您需要使用的语言取决于要实现的目标。

基本的jquery设置将如下所示:

$(document).ready(function(){
$(".like").click(function() {
  var contentpk = $(this).data('contentpk');
    $.ajax({
        url: "//", //your like_post url should go here, you can use the variable created above (contentpk) if that is in your url
        success: function(result) {
        }});
      });
    });

您的html需要进行一些更改:

{% if user not in content.liked.all %}
  <a class="btn like" href="javascript:" data-content="{{content.pk}}">Like</a>
{% else %}
  <a class="btn like" href="javascript:" data-content="{{content.pk}}">Unlike</a>
{% endif %}

这还假设您的html中已经有了jquery cdn脚本。