use slugify in template

前端 未结 2 1214

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

(ur\'^company/news/(?P.*)/(?P\\d+)/$\',\'C         


        
2条回答
  •  悲哀的现实
    2021-02-13 10:16

    This will generate the needed url:

    {% for n in news %}
          {{n.description}}
    {% 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 %}
    

    renders as:

    ying-shi-ma-1-2-3
    

提交回复
热议问题