django - Convert a title with spaces to a url-friendly title like stackoverflows title -


i have blog app list of latest post titles. list item should linked content. problem (similar post) if title has spaces url spaces if use:

<a href="{{  i.id  }}/{{  i.title  }}">{{ i.title }} 

in template. use additional urlfield dont want create url-friendly title manually. what's common way this?

my models.py

class post(models.model):     title = models.charfield(max_length=100)     ...      def __unicode__(self):         return self.title 

my view.py

def recentlyblogged(request):     lastposts = post.objects.filter(publication__gt = datetime.now() - timedelta(days=30))     return render(request, "blog/blog.html", {'posts': lastposts}) 

my template

{% in posts %}     <ul id="latestpostslist">         <li class="latestpostslistitem"><a href="{{  i.id  }}/{{  i.title  }}">{{ }}</a></li> {% endfor %}     </ul> 

you looking slug.

try this

from django.template.defaultfilters import slugify class post(models.model):     title = models.charfield(max_length=100)     ...      def __unicode__(self):         return self.title      def get_absolute_url(self):         return reverse('post_url', args=(slugify(self.title), )) 

and in template,

<a href="{{  i.get_absolute_url }}">{{ i.title }}</a> 

you might have modify urls.py accordingly too

url(r'post_url/(?p<slug>[\w-]+)/', view_name, name="post_url") 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -