如何在 Django 中使用 @ 提及用户 [英] How to mention users using @ in django

查看:30
本文介绍了如何在 Django 中使用 @ 提及用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 django 上做一个项目,它与 instagram 和 twitter 非常相似,它需要具备的功能之一是提及使用@"的用户;在文本字段中.我已经调查了一段时间关于如何在 django 中做到这一点,除了像 django-mentions 这样的库我不明白它是如何工作的,我几乎一无所获,但我也发现使用 react 是可能的,但是我不知道是否可以对几乎完成的 django 项目实施反应.这个功能如何工作?我应该使用 react 还是任何 javascript?

I have been working on a project on django and it is very similar to instagram and twitter, one of the functions it needs to have is to mention users using "@" in text fields. I have been investigation a little while now on how I can do that in django and I have found litteraly nothing except some libraries like django-mentions which I don't understand how it works but I have also found that this is possible using react but I don't know if it is possible to implement react to an almost finished django project. How can this function work? Should I use react or any javascript?

models.py

class Post(models.Model):
    text = models.CharField(max_length=200)
    user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')

views.py(上传视图包含存储帖子的表单以供稍后显示,主视图显示上传的帖子)

views.py (upload view contains the form that stores the post to later display it and main view displays the uploaded post)

def upload(request):

    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('home')
            print('succesfully uploded')

    else:
        form = PostForm()
        print('didnt upload')
    return render(request, 'home.html', {'form': form})

def main(request):
    contents = Post.objects.all()

    context = {
        "contents": contents,
    }
    print("nice2")
    return render(request, 'home.html', context)

forms.py

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('text')
        exclude = ['user']

html(上传带有文本的帖子的表单,用户可以在其中键入@mentions)

html (form that uploads a post with text in which the user can type @mentions)

<form method="post" action="{% url 'upload' %}" enctype="multipart/form-data">        
    {% csrf_token %}
    <input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
    <button class="submit-button" type="submit">Save</button>
</form>

html(这里是帖子的显示位置)

html (Here is where the post is displayed)

{% for content in contents %}
    {% if contents %}
        <div class="element"><p>{{ content.text }}</p></div>
    {% endif %}
{% endfor %}

如果您有任何问题,请告诉我,记住任何想法都会有所帮助.

Please if you have any questions please let me know, rememnber that any idea helps.

推荐答案

您实际上可以构建您的 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

这篇关于如何在 Django 中使用 @ 提及用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆