0

I've been trying slugify a CharField in my models. I've followed this tutorial but I've only managed to get a Database error. "column article_article.slug does not exist. I'm aware of South and migrations but I'm I haven't used it properly. Basically I have a blog application and each post is identified by an ID number. I want to slugify the titles for each blog post.

Here's my views.py

def article(request, article_id =1):
    return render_to response('article.html', {'article':Article.Objects.get(id=article_id)}, context_instance=ResquestContext(request))

Here's my models.py

class Article(models.Model):
    title = models.CharField(max_length=30) #<--want to slugify this
    body = models.TextField()
    pub_date = models.DateTimeField('date published')
    likes = models.IntegerField(default = 0)

    def __unicode__(self):
         return self.title

Here's my urls.py

...
url(r'^get/(?P<article_id>\d+)/$', 'article.views.article'),
...

Here's my articles.html

 ...
 <a id = "title2" href="articles/get{{ article.id }} /"> {{ article.title }} </a>
 ...
DapperMan
  • 21
  • 2

1 Answers1

0

Hope this helps you! You need to create a slug field.

class Article(models.Model):
        title = models.CharField(max_length=30)
        slug = models.SlugField() #slug field
        body = models.TextField()
        pub_date = models.DateTimeField('date published')
        likes = models.IntegerField(default = 0)

        def __unicode__(self):
             return self.title

        def save(self, *args, **kwargs):
             if self.title == None or self.title == '':
                   self.title = _infer_title_or_slug(self.text.raw)

             if self.slug == None or self.slug == '':
                   self.slug = slugify(self.title)

             i = 1
             while True:
                 created_slug = self.create_slug(self.slug, i)
                 slug_count = Article.objects.filter(slug__exact=created_slug).exclude(pk=self.pk)
                 if not slug_count:
                      break
                 i += 1
             self.slug = created_slug

             #your other code

             #call the "real" save method
             super(Article, self).save(*args, **kwargs)


        def create_slug(self, initial_slug, i=1):
             if not i==1:
                 initial_slug += "-%s" % (i,)
             return initial_slug
Anish Shah
  • 7,669
  • 8
  • 29
  • 40