[英]django url-tag and decorated urls
I'm writing a small blog-app and want its entries to be accessible via a combination of the title-name and the id. 我正在写一个小博客应用程序,并希望通过title-name和id的组合来访问它的条目。
Expression: ^blog/([\d\w\-_]+)\-(\d+)/$
Example URL: localhost:8000/blog/django-is-awesome-231/
The first part is generated by converting the blog-entries' title all to lowercase and replace spaces and special characters with -
. 第一部分是通过将博客条目的标题全部转换为小写并将空格和特殊字符替换为
-
。
I was wondering how I can reverse such an URL from an entry. 我想知道如何从条目中反转这样的URL。
{% for entry in entries %}
<li><a href="{% url 'blog.views.display', entry.title entry.id %}">{{ entry.title }}</a></li>
{% endfor %}
But it tells me that no reverse match was found. 但它告诉我没有找到反向匹配。
Thanks, 谢谢,
I just tried it this way: 我只是这样尝试:
def get_mangled_name(self):
""" Returns the mangled name of the entry. """
title = self.title.lower().replace(' ', '-')
title = ''.join(filter(lambda x: x in string.letters, title))
if title.endswith('-'):
title = title[:1]
return '%s-%d' % (title, self.id)
<li><a href="{% url 'blog.views.display' entry.get_mangled_name %}">{{ entry.title }}</a></li>
But it didn't work either. 但它也没有用。
There's a slugify
template filter that will convert a title into a slug. 有一个
slugify
模板过滤器,将标题转换为slug。 So, you could write your template code like: 所以,您可以编写模板代码,如:
{% url 'blog.views.display', entry.title|slugify entry.id %}
However, any time you're dealing with slugs, you should actually have a slug
field on your model to store the value permanently. 但是,每当你处理slug时,你的模型上应该有一个
slug
字段来永久存储值。 At the very least, you should probably take César's advice and do this in get_absolute_url
instead. 至少,您应该接受César的建议,并在
get_absolute_url
执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.