use slugify in template

我是研究僧i 提交于 2019-12-04 18:12:02

问题


I want to have SEO-friendly URL,my current url in urls.py :

(ur'^company/news/(?P<news_title>.*)/(?P<news_id>\d+)/$','CompanyHub.views.getNews')

I use it in template:

{% for n in news %}
     <a href="{% url CompanyHub.views.getNews n.title,n.pk %}" >{{n.description}}</a>
{% endfor %}

I use news_id to get news object with that PK . I want to convert this url:

../company/news/tile of news,with comma/11

to:

../company/news/tile-of-news-with-comma/11

by doing some thing like this in template:

{% for n in news %}
      <a href="{% url CompanyHub.views.getNews slugify(n.title),n.pk %}" >{{n.description}}</a>
{% endfor %}

I checked out these questions: question1 question2 question3 and this article but they save an slugify field in database while I wanna generate it on demand.in addition I want to run a query by news_id.

I think this question is good,but I don't know how to use news_id to fetch my news object


回答1:


This will generate the needed url:

{% for n in news %}
      <a href="{% url CompanyHub.views.getNews n.title|slugify n.pk %}" >{{n.description}}</a>
{% endfor %}

The examples above save slugify_field in database, as they later search for it. Otherwise in database you'll have a normal title, and slugified title in code for searching.. No easy way to compare them. But the way you've explained is simpler. You will have this kind of view:

def news(request, slug, news_id):
    news = News.objects.filter(pk=news_id)

UPDATE: To use unicode symbols in slugify, you'll need a conversion first. Look at this: How to make Django slugify work properly with Unicode strings?. It uses the Unidecode library

Then add a custom filter:

from unidecode import unidecode
from django.template.defaultfilters import slugify

def slug(value):
    return slugify(unidecode(value))

register.filter('slug', slug)

then in your template use this:

{% load mytags %}
<a href="{% url CompanyHub.views.getNews n.title|slug n.pk %}

Here is an example:

{{ "影師嗎 1 2 3"|slug}}

renders as:

ying-shi-ma-1-2-3



回答2:


Have you tried n.title|slugify and see if that works for you.

ref: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#slugify

Note: although this is possible, just make sure the 'slugified' element is never used for any part of routing... (ie, purely for display only)



来源:https://stackoverflow.com/questions/11455812/use-slugify-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!