diff options
author | Dan McGee <dan@archlinux.org> | 2010-09-20 16:21:08 -0500 |
---|---|---|
committer | Dan McGee <dan@archlinux.org> | 2010-09-21 09:10:02 -0500 |
commit | 1b6cf5261c2a87c507fef290bf9d2af5606c8451 (patch) | |
tree | dcf1b37507ec58f2f9273213a38b3843f78a847d | |
parent | 41dc37c8126f062257ce7d5fc8fcf84286b55a88 (diff) |
Auto-populate slug on news item creation
And make sure it is unique through a few queries and some magic.
Signed-off-by: Dan McGee <dan@archlinux.org>
-rw-r--r-- | news/views.py | 18 | ||||
-rw-r--r-- | urls.py | 2 |
2 files changed, 17 insertions, 3 deletions
diff --git a/news/views.py b/news/views.py index 7fa92c8a..f3d7312f 100644 --- a/news/views.py +++ b/news/views.py @@ -2,6 +2,7 @@ from django import forms from django.contrib.auth.decorators import permission_required from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect +from django.template.defaultfilters import slugify from django.views.decorators.cache import never_cache from django.views.generic import list_detail, create_update from django.views.generic.simple import direct_to_template @@ -21,7 +22,7 @@ def view(request, slug=None): template_object_name='news') #TODO: May as well use a date-based list here sometime -def list(request): +def news_list(request): return list_detail.object_list(request, News.objects.all().select_related('author').defer('content'), paginate_by=50, @@ -31,7 +32,19 @@ def list(request): class NewsForm(forms.ModelForm): class Meta: model = News - exclude=('id', 'author', 'postdate') + exclude=('id', 'slug', 'author', 'postdate') + +def find_unique_slug(newsitem): + '''Attempt to find a unique slug for this news item.''' + existing = list(News.objects.values_list('slug', flat=True).distinct()) + + suffixed = slug = slugify(newsitem.title) + suffix = 0 + while suffixed in existing: + suffix += 1 + suffixed = "%s-%d" % (slug, suffix) + + return suffixed @permission_required('news.add_news') @never_cache @@ -41,6 +54,7 @@ def add(request): if form.is_valid(): newsitem = form.save(commit=False) newsitem.author = request.user + newsitem.slug = find_unique_slug(newsitem) newsitem.save() return redirect(newsitem.get_absolute_url()) else: @@ -69,7 +69,7 @@ urlpatterns = patterns('', (r'^news/(?P<slug>[-\w]+)/$', 'news.views.view'), (r'^news/(?P<slug>[-\w]+)/edit/$', 'news.views.edit'), (r'^news/(?P<slug>[-\w]+)/delete/$', 'news.views.delete'), - (r'^news/$', 'news.views.list', {}, 'news-list'), + (r'^news/$', 'news.views.news_list', {}, 'news-list'), (r'^mirrors/$', 'devel.views.mirrorlist', {}, 'mirrors-list'), |