我有content
='请告诉我你谈到的Python书,@ friend'
然后在我的 views.py :
中 new_content = re.sub(r'(@\w+)', r"<a href='#'>\g<0></a>>", content)
返回
new_content = 'Please get me the Python book you talked about, <a href='#'>@friend</a>'
我想如果用户点击@friend
,则应该重定向到此网址:
url(r'^user/(?P<user_name>\w+)/$', views.profile, name='profile'),
如何在我的 views.py 中将此网址(profile
)包含在<a href='#'></a>
中,就像我在Django模板中所做的那样<a href="{% url 'mysite:profile' user.username %}">@{{user.username}}</a>
?
答案 0 :(得分:3)
你使用reverse()
return HttpResponseRedirect(reverse('url_name'))
您可以查看answer for reference. 和documentation for the function.
您可能需要传递参数。你可以这样做:
reverse('profile', kwargs={'user_name': 'auth'})
对于您的情况,您可以尝试:
content = 'Please get me the Python book you talked about, @friend'
new_content = re.sub(r'(@\w+)', r"<a href='%s'>\g<0></a>>" % (reverse('profile', kwargs={'user_name': 'friend_username'})), content)
答案 1 :(得分:0)
您已将其参数命名为user_name
# urls.py
url(r'^user/(?P<user_name>\w+)/$', views.profile, name='profile'),
# views.py
from django.views.generic.detail import DetailView
class UserDetailView(DetailView):
"""
Takes keyword argument 'user_name'
and looks for it in database:
User.objects.get(username='dude')
"""
model = User
slug_field = 'username'
context_object_name = 'user'
slug_url_kwarg = 'user_name'
template_name = 'user_detail.html'
# Pass your keyword argument
<a href="{% url 'mysite:profile' user_name=user.username %}">@{{ user.username }}</a>