python - Like button Django3 - KeyError at /nutriscore/exemple-1/ 'pk'
问题描述
我希望你很好。我是 Python 的初学者,我正在尝试在这样的博客文章中实现一个类似的按钮。在管理部分,我可以看到谁在点击类似的东西。
但是我遇到两个问题:
- 第一个:当我点击点赞按钮时,“返回”会使用这种 url nutricore/4/ 重定向我,或者我的文章使用 slug(比如 /nutriscore/exemple-1/。你知道吗?
- 第二个:当我想显示喜欢 {{ total_likes }} 的数量时,我遇到了这个问题: KeyError at /nutriscore/exemple-1/ 'pk'
模型.py:
class Post(models.Model):
...
likes = models.ManyToManyField(User, related_name='nutriscore_posts')
def total_likes(self):
return self.likes.count()
视图.py:
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[str(pk)]))
class PostDetail(generic.DetailView):
model = Post
context_object_name = 'post'
template_name = 'post_detail.html'
def get_context_data(self, **kwargs):
context = super(PostDetail, self).get_context_data(**kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes
context['total_likes'] = total_likes
return context
网址.py
path('like/<int:pk>', LikeView, name="like_post"),
post_detail.html
<form action="{% url 'like_post' post.pk %}" method="POST">{% csrf_token %}<button type="submit" name="post_id" value="{{ post.id }}" class="cherry-likes"><img src="static/img/like.png" width="30px" height="30px" class="" title=""></button></form>
非常感谢 :)
解决方案
第一个问题:你将 pk 传递给重定向,它是一个整数(根据你的 urls.py)到 url: args=[str(pk)]
。如果你想重定向到一个url,/nutriscore/exemple-1
你应该传递slug而不是pk(我猜这是id)并相应地调整你的urls.py。
第二个问题:你确定那个帖子有一个叫做pk的属性/键吗?这不应该是身份证吗?喜欢:
<form action="{% url 'like_post' post.id %}" method="POST">{% csrf_token %}<button type="submit" name="post_id" value="{{ post.id }}" class="cherry-likes"><img src="static/img/like.png" width="30px" height="30px" class="" title=""></button></form>
推荐阅读
- javascript - 如何从 Express Server 中的不同文件夹加载 API 端点?
- neo4j - neo4j neosemantics:加载模型约束
- python - Matplotlib 散点图中的分组值
- classification - weka 对输出的简单逻辑回归解释
- c# - 如何生成 sql 命令以使用其他列更新主键
- node.js - TypeError:Joi.validate 不是节点 js 中的函数
- python - 尽管文件不仅仅是换行符,但从 .docx 文件中读取会产生换行符
- python - 以可理解的形式重写 for 循环
- python - 如何在类中获取方法的变量?
- apache - 无限地址嵌套