如何在django通知中使用动作对象和目标



我正在用django做一个项目,类似于webapp的博客。我使用django通知来通知我的网站。如果有人对我的帖子发表评论或喜欢我的帖子,我会收到通知。但是,我无法通过单击通知从通知转到特定的帖子。我的观点.py:

@login_required
def like_post(request):
# posts = get_object_or_404(Post, id=request.POST.get('post_id'))
posts = get_object_or_404(post, id=request.POST.get('id'))
# posts.likes.add for the particular posts and the post_id for the post itself its belongs to the post without any pk
is_liked = False
if posts.likes.filter(id=request.user.id).exists():
posts.likes.remove(request.user)
is_liked = False
else:
posts.likes.add(request.user)
is_liked = True
notify.send(request.user, recipient=posts.author, actor=request.user, verb='liked your post.', nf_type='liked_by_one_user')
context = {'posts':posts, 'is_liked': is_liked, 'total_likes': posts.total_likes(),}

if request.is_ajax():
html = render_to_string('blog/like_section.html', context, request=request)
return JsonResponse({'form': html})

从项目的自述文件中,我们可以看到Notification模型允许您在JSON字段中存储额外的数据。要启用此功能,您首先需要将其添加到您的设置文件中

DJANGO_NOTIFICATIONS_CONFIG = { 'USE_JSONFIELD': True}

完成此操作后,您可以将目标对象的url存储在字段中,方法是将其作为kwarg传递给notify.send信号

notify.send(request.user, recipient=posts.author, actor=request.user, verb='liked your post.', nf_type='liked_by_one_user', url=object_url)

但是,您应该注意,如果您更改url conf,这样做会导致链接断开,因此另一种方法是创建一个返回目标对象url的视图,您可以在呈现通知时调用该视图。

最新更新