使用slugify in temp

2024-04-30 00:50:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想拥有SEO-friendly URL,我当前的url在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_idget新闻对象。 我要转换此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 %}

我检查了这些问题: question1question2question3和这个article但是它们在数据库中保存了一个slugify field,而我想按需生成它。此外,我想通过news_id运行一个查询。

我觉得这个question不错,但我不知道如何使用news_id来获取我的news object


Tags: in模板idurlfortitledescriptioncompany
2条回答

你有没有试过n.title|slugify看看这是否适合你。

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

注意:尽管这是可能的,但请确保“slugified”元素从未用于路由的任何部分。。。(即,仅供展示)

这将生成所需的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

相关问题 更多 >