问题描述
我想拥有 SEO友好网址
,我当前的URL位于 urls.py
中:
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')
我在模板中使用它:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews n.title,n.pk %}" >{{n.description}}</a>
{% endfor %}
我使用 news_id
到获取
新闻对象与 PK
。
我想转换此网址:
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 %}
我查了这些问题:
和这个,但是他们在数据库中保存了一个 slugify字段
想要根据需要生成它。此外,我想通过 news_id
运行查询。
I checked out these questions:question1question2question3 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
.
我认为这个很好,但我不知道如何使用 news_id
获取我的新闻对象
I think this question is good,but I don't know how to use news_id
to fetch my news object
推荐答案
这将产生所需的url:
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 %}
上面的示例保存 slugify_field
,因为他们后来搜索它。否则在数据库中,您将有一个正常的标题,并在代码中标题搜索..没有简单的方法来比较它们。但是你解释的方法比较简单。你会有这样的观点:
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)
更新:使用unicode符号在淘汰中,您需要首先进行转换。看看这个:库
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 %}
这是一个例子:
{{ "影師嗎 1 2 3"|slug}}
呈现为:
ying-shi-ma-1-2-3
这篇关于在模板中使用slugify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!