django - 如何在 django 通知中使用动作对象和目标
问题描述
我正在使用 django 开发一个项目,比如 webapp 之类的博客。我正在使用 django 通知来通知我的网站。如果有人对我的帖子发表评论或喜欢该帖子,我会收到通知。但是我不能去具体的通过单击通知从通知中发布。我的views.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。
推荐阅读
- javascript - VueJS线性量规不呈现
- c# - 名称中带有“Id”的可空 int 属性上的无效 ModelState .NET Core
- javascript - 将字符串变量传递给 Moment.js 减法函数
- c# - How to set template for listbox in WPF(Windows 10 Weather)
- javascript - 如何通过javascript缩小文本以适合Illustrator中的给定矩形?
- extjs - 输入组合框时值消失
- yii - 为在 yii1 PHP 框架中不起作用的文本框添加增量变量和 id 名称
- wordpress - 我的 jQuery 函数在移动设备上的 Google Chrome 上不起作用
- d3.js - Firefox cshtml 中的 D3.JS 条形图
- dart - 如何在一行中设置文本以进行颤动