I want to have SEO-friendly URL
,my current url in urls.py
:
(ur\'^company/news/(?P.*)/(?P\\d+)/$\',\'C
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)
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