Python 将帖子中提到的用户名作为配置文件链接返回到帖子中的用户
嘿,伙计们,我正试图让我的代码检查在一篇文章中提到的一个数据库中有@username的用户,并将该用户配置文件链接作为@username返回。我目前可以在我的视图中使用taged_users变量获取后端的用户。它存储提到的用户,但我如何在模板中访问这些用户,以便它为我提供指向这些用户配置文件的链接?到目前为止,我的代码在模板中是这样的Python 将帖子中提到的用户名作为配置文件链接返回到帖子中的用户,python,django,python-3.x,django-templates,django-views,Python,Django,Python 3.x,Django Templates,Django Views,嘿,伙计们,我正试图让我的代码检查在一篇文章中提到的一个数据库中有@username的用户,并将该用户配置文件链接作为@username返回。我目前可以在我的视图中使用taged_users变量获取后端的用户。它存储提到的用户,但我如何在模板中访问这些用户,以便它为我提供指向这些用户配置文件的链接?到目前为止,我的代码在模板中是这样的 {% if post.post|slice:":1" == '@' %} <a href="{% url 'profile_with_pk' pk=u
{% if post.post|slice:":1" == '@' %}
<a href="{% url 'profile_with_pk' pk=user.username %}">
{{ post.post }}
</a>
{% else %}
{{ post.post }}
{% endif %}
有很多问题。让我们从这个开始:
<a href="{% url 'profile_with_pk' pk=user.username %}">
{{ post.post }}
</a>
整个帖子都用链接包起来了。我想你想链接到这篇文章的作者,对吗?然后(仅猜测您没有发布的模型模式),您需要这样的东西:
# iteration through posts somewhere here
<a href="{% url 'profile_with_pk' pk=user.username %}">user.username</a>
{{ post.post }}
#在此处某处的帖子中迭代
{{post.post}}
其次,如果您已经标记了用户,那么您需要以某种方式将其放入您的帖子中的模板中。根据您希望将链接放置到提及用户的方式,这可能类似于:
# iteration through posts somewhere here
<a href="{% url 'profile_with_pk' pk=user.username %}">user.username</a>
{{ post.post }}
Mentions: {% for tagged_user in tagUsers %} {{ tagged_user.username }} {% endfor %}
#在此处某处的帖子中迭代
{{post.post}}
提到:{%tagUsers%}{{Tagked_user.username}{%endfor%}
或者你想直接在文章中插入链接?然后,在将其传递给模板之前,您需要构建一个post结构(示例被截断;需要改进):
从django.utils.html导入标记\u safe
def post(自我、请求、主键=无):
...
post_text=post.post
tagUsers=re.findall(r“@+(\w+),post.post)
标记的用户=列表()
对于标记用户中的用户名:
user=user.objects.get(用户名=username)
对于re.finditer中的匹配(用户名、发布文本):
start=match.start()
end=match.end()
profile_link=reverse('profile_with_pk',kwargs={'pk':user.id})
post_文本[开始:结束]=标记_安全(f'')
...
#将post_文本返回到模板上下文,并以与使用post相同的方式使用
你帮了这么多忙,我能给你买杯咖啡什么的吗?非常感谢你没有你真正的天使我将尝试其中的一些,看看我是否能得到想要的结果谢谢
# iteration through posts somewhere here
<a href="{% url 'profile_with_pk' pk=user.username %}">user.username</a>
{{ post.post }}
Mentions: {% for tagged_user in tagUsers %} {{ tagged_user.username }} {% endfor %}
from django.utils.html import mark_safe
def post(self, request, pk=None):
...
post_text = post.post
tagUsers = re.findall(r"@+(\w+)", post.post)
tagged_users = list()
for username in tagUsers:
user = User.objects.get(username=username)
for match in re.finditer(username, post_text):
start = match.start()
end = match.end()
profile_link = reverse('profile_with_pk', kwargs={'pk': user.id})
post_text[start:end] = mark_safe(f'<a href="{profile_link}">username</a>')
...
# return post_text to template context and use in the same way as used post