我想要 SEO 友好的 URL
,我在 urls.py
中的当前 url:
(ur'^company/news/(?P<news_title>.*)/(?P<news_id>\d+)/$','CompanyHub.views.getNews')
我在模板中使用它:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews n.title,n.pk %}" >{{n.description}}</a>
{% endfor %}
我使用 news_id
来获取
news 对象与 PK
。
我想转换这个 url:
../company/news/tile of news,with comma/11
到:
../company/news/tile-of-news-with-comma/11
通过在模板中做这样的事情:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews slugify(n.title),n.pk %}" >{{n.description}}</a>
{% endfor %}
我检查了这些问题:
question1
question2
question3还有这个article但他们在数据库中保存了一个 slugify 字段
,而我想按需生成它。此外,我想通过 news_id
运行查询。
我觉得这个question很好,但我不知道如何使用 news_id
来获取我的 news 对象
最佳答案
这将生成所需的 url:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews n.title|slugify n.pk %}" >{{n.description}}</a>
{% endfor %}
上面的示例将 slugify_field
保存在数据库中,因为他们稍后会搜索它。否则在数据库中你将有一个正常的标题,以及用于搜索的代码中的标题。没有简单的方法来比较它们。但是你解释的方式更简单。你会有这样的看法:
def news(request, slug, news_id):
news = News.objects.filter(pk=news_id)
更新:要在 slugify 中使用 unicode 符号,您需要先进行转换。看看这个:How to make Django slugify work properly with Unicode strings? .它使用 Unidecode图书馆
然后添加自定义过滤器:
from unidecode import unidecode
from django.template.defaultfilters import slugify
def slug(value):
return slugify(unidecode(value))
register.filter('slug', slug)
然后在你的模板中使用这个:
{% load mytags %}
<a href="{% url CompanyHub.views.getNews n.title|slug n.pk %}
这是一个例子:
{{ "影師嗎 1 2 3"|slug}}
呈现为:
ying-shi-ma-1-2-3
关于python - 在模板中使用 slugify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11455812/