S
S
S0ulReaver2012-02-20 20:08:37
Django
S0ulReaver, 2012-02-20 20:08:37

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

6 answer(s)
3
3ds, 2012-02-20
@S0ulReaver

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 }}

J
jov, 2012-02-20
@jov

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.

E
EvoTech, 2012-02-21
@EvoTech

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

A
admin4eg, 2012-02-21
@admin4eg

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)

in functions.py file
import trans

def createUid(uid):
  return uid.encode('trans').replace(' ', '_').lower();

The url is like this
/blog/post/149-eroticheskie_gifki.html

K
Konstantin Kitmanov, 2012-02-21
@k12th

Model.SlugField, django.template.defaultfilters.slugify

S
Stanislav, 2012-02-20
@crackedmind

I just generated uuid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question