且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Django 中使用 @ 提及用户

更新时间:2022-06-26 07:49:51

您实际上可以构建您的 custom-template 标签来检查 @(pattern) 在任何你想要的字段中,并且只有在自定义标签功能中你才能检查是否用户是否存在(如果存在)然后做任何你想做的事情(比如创建通知或链接到提到的用户个人资料)

You can actually build your custom-template tag to check for the @(pattern) in whatever field you want and in the custom tag function only you can check whether the user exists or not if exists then do whatever you want(like creating notification or linking to mentioned user profile)

######这样的事情#######

######something like this #######

  @register.filter(name='mention', is_safe=True)
  @stringfilter
  def mention(value):
     res = ""
     my_list = value.split()
     for i in my_list:
        if i[0] == '@':
            try:
              stng = i[1:]
              user = User.objects.get(username = stng)
              if user:
                 profile_link = user.userprofile.get_absolute_url()
                 i = f"<a href='{profile_link}'>{i}</a>"

            except User.DoesNotExist:
            print("Could not get the data")

      res = res + i + ' '
    
   return res

但是,为了提高效率,您还可以使用正则表达式来查找模式.现在添加名为提及"的标签.到您的 HTML 并且不要忘记加载标签

however, to be more efficient u can also use regex to find the pattern. Now add the tag named "mention" to your HTML and don't forget to load the tag