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

查看:50
本文介绍了如何在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

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.

推荐答案

您实际上可以构建

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

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

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