【问题标题】:How to mention users using @ in django如何在 django 中使用 @ 提及用户
【发布时间】:2020-11-02 21:43:53
【问题描述】:

我一直在 django 上做一个项目,它与 instagram 和 twitter 非常相似,它需要具备的功能之一是在文本字段中使用“@”来提及用户。我一直在调查我如何在 django 中做到这一点,除了一些像 django-mentions 这样的库,我几乎没有发现任何东西,我不明白它是如何工作的,但我也发现使用 react 是可能的,但是我不知道是否可以对一个几乎完成的 django 项目实施反应。这个功能如何工作?我应该使用 react 还是任何 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(上传视图包含存储帖子以供稍后显示的表单,主视图显示上传的帖子)

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)

<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(这里是显示帖子的地方)

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

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

【问题讨论】:

标签: javascript django reactjs django-models django-views


【解决方案1】:

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

######类似这样的东西 #######

  @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 中,不要忘记加载标签

【讨论】:

    【解决方案2】:

    我发现 that 的帖子有助于使用 martor 文本编辑器的想法,但这并不难。

    在我的应用中,我有一个包含 Profile 模型的帐户应用,用于将提及链接 @[user] 重定向到用户的个人资料

    models.py

    from django.contrib.auth.models import User
    class Profile(models.Model):
      user= models.OneToOneField(User, on_delete=models.CASCADE)
    

    urls.py

    path('profile/<str:user>/',views.profile, name='profile'),
    

    views.py

    from . models import Profile
    def profile(request,user):
    the_user= User.objects.get(username=user)
    profile= Profile.objects.get(user=the_user)
    return render(request, 'profiles/profile.html',{'profile': profile})
    

    settings.py

    MARTOR_MARKDOWN_BASE_MENTION_URL = '/accounts/profile/'
    

    然后编辑器继续提及用户@[user] /accounts/profile/user

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 2017-10-13
      • 2017-04-07
      • 2020-09-06
      • 2021-10-24
      • 2012-11-03
      • 2021-07-01
      • 1970-01-01
      • 2020-05-04
      相关资源
      最近更新 更多