Answer the question
In order to leave comments, you need to log in
Django: how to generate a unique URL for a news item?
I am learning Django. In general, the task is typical, but so far sensible options do not come to mind. There is a website, it has news, you need to somehow generate a unique URL for each of them. Presumably, this can be done based on the date + some other unique identifier, but I can’t decide how it should work: to form a URL somehow using the template system, or to store a URL for each news in the database and substitute it in the template . Also, I still have not decided how to provide this very “uniqueness”.
Somebody will prompt the normal decision - implementation of the task? Well, or again, mb somewhere you can take the source of some kind of blog on Django to dig?
Answer the question
In order to leave comments, you need to log in
I did this (we refer to the news 20120221-1 - date-id):
url.py -
url(r'^news/(?P(\d){8})?(\-)?(?P(\d)+)?$', news_views.show_news, name="news-url"),
models.py:
class News(models.Model):
...........
def get_absolute_url(self):
return "/news/%s" % (self.news_date.strftime('%Y%m%d') + '-' + str(self.id))
template.html:
{{ news.title }}
If you like CNC and the idea of breadcrumbs, then /year/month/day/id-slug scheme is preferable? for DetailView. The user can always view news for a certain period, ListView, simply by modifying the url in the browser line, in a completely logical way.
As far as I understand, you are interested in the question that a header-based slug may not be unique and needs to be suffixed (if it already exists in the database). The first thing that came to hand is bitbucket.org/neithere/django-autoslug
In general, www.google.com/search?hl=ru&q=django+autoslug
I have something like this
class Post(models.Model):
title = models.CharField(max_length=64, verbose_name='Заголовок поста')
uid = models.CharField(max_length=64, unique=True, blank=True, verbose_name='Url')
...........
def get_absolute_url(self):
return '/blog/post/%s.html' % self.uid
def save(self, *args, **kwargs):
if not self.uid:
lastid = Post.objects.latest('id')
self.uid = str(lastid.id + 1 ) +'-'+ createUid(self.title)
super(Post, self).save(*args, **kwargs)
import trans
def createUid(uid):
return uid.encode('trans').replace(' ', '_').lower();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question