简体   繁体   中英

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.

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.

{% 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. 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. At the very least, you should probably take César's advice and do this in get_absolute_url instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM