喜欢没有在django中出现的数量

时间:2018-05-17 04:39:21

标签: python django

我是django的新手,并尝试在我的post_list页面中实现like按钮。它显示了喜欢的选项,但当我点击它时,页面只是刷新。它没有显示总喜欢,我也希望页面重定向到post_detail。有人可以帮我这个吗? 谢谢。

HTML

<!DOCTYPE html>
{% extends 'home.html' %}
{% load staticfiles %}
{% block content %}
<div class="centerstage">
{% for post in post_list %}
    <div class="post">
        <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
        <div class="date">
            <p>Published on: {{ post.published_date|date:"D M Y"}}</p>
        </div>
        <p><a class='like-btn' data-href='{{ obj.get_api_like_url }}' data-likes='{{ obj.likes.count }}'  href='{{ obj.get_like_url }}'>
          {{ obj.likes.count }} Agree</a></p>

          <form method = "post">
            {% csrf_token %}

          </form>
          <a href="{% url 'post_detail' pk=post.pk %}">Comments: {{ post.approve_comments.count }}</a>
    </div>
{% endfor %}
</div>
{% endblock %}

models.py

class Post(models.Model):
    author           =       models.ForeignKey(User, on_delete = models.CASCADE)
    title            =       models.CharField(max_length=200)
    slug             =       models.SlugField(unique=True, blank=True, default=uuid.uuid1)
    text             =       models.TextField()
    created_date     =       models.DateTimeField(default=timezone.now)
    published_date   =       models.DateTimeField(blank=True, null=True)
    likes = models.ManyToManyField(User, related_name='post_likes', blank = True)

def get_like_url(self):
    return reverse("posts:like-toggle", kwargs={"slug": self.slug})

def get_api_like_url(self):
    return reverse("posts:like-api-toggle", kwargs={"slug": self.slug})

def publish(self):
    self.published_date = timezone.now()
    self.save()

views.py

class PostLikeToggle(RedirectView):

def get_redirect_url(self, *args, **kwargs):
    slug = self.kwargs.get("slug")
    print(slug)
    obj = get_object_or_404(Post, slug=slug)
    url_ = obj.get_absolute_url()
    user = self.request.user
    if user.is_authenticated():
        if user in obj.likes.all():
            obj.likes.remove(user)
        else:
            obj.likes.add(user)
    return url_
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions

class PostLikeAPIToggle(APIView):
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (permissions.IsAuthenticated,)

def get(self, request, slug=None, format=None):
    # slug = self.kwargs.get("slug")
    obj = get_object_or_404(Post, slug=slug)
    url_ = obj.get_absolute_url()
    user = self.request.user
    updated = False
    liked = False
    if user.is_authenticated():
        if user in obj.likes.all():
            liked = False
            obj.likes.remove(user)
        else:
            liked = True
            obj.likes.add(user)
        updated = True
    data = {
        "updated": updated,
        "liked": liked
    }
    return Response(data)


class PostListView(ListView):
model = Post

def get_queryset(self):
    return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')

urls.py

from django.conf.urls import url
from . import views
from django.contrib import admin

urlpatterns = [
url(r'^post/post_list/$',views.PostListView.as_view(),name='post_list'),
url(r'^(?P<slug>[\w-]+)/like/$', views.PostLikeToggle.as_view(), name='like-toggle'),
url(r'^api/(?P<slug>[\w-]+)/like/$',views.PostLikeAPIToggle.as_view(), name='like-api-toggle'),
]

1 个答案:

答案 0 :(得分:1)

由于您在for循环中命名变量post,因此应在循环内使用post。它应该是

<p><a class='like-btn' data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}'  href='{{ post.get_like_url }}'>
          {{ post.likes.count }} Agree</a></p>

而不是

<p><a class='like-btn' data-href='{{ obj.get_api_like_url }}' data-likes='{{ obj.likes.count }}'  href='{{ obj.get_like_url }}'>
          {{ obj.likes.count }} Agree</a></p>