且构网

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

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

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

您实际上可以构建

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

但是,要提高效率,您还可以使用正则表达式来查找模式.现在添加名为"mention"的标签,到您的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