Search code examples
pythondjangotagging

ValueError while using AutoSlugField and Django-tagging


Am running into ValueError, here is the full traceback, the end of which is:

Exception Type: ValueError at /admin/blog/post/add/
Exception Value: invalid literal for int() with base 10: 'treef'

I'm using AutoSlugField from django-command-extensions.

I am trying to get django-tagging working, this is my models.py:

class Post(models.Model):
  """Blog post model."""
  title = models.CharField('title', max_length=120)
  slug = AutoSlugField('slug', unique=True, max_length=120, primary_key=True)
  body = models.TextField('body')
  published = models.DateTimeField('publish', default=datetime.now)
  category = models.ForeignKey(Category)
  tags = TagField()

  class Meta:
    verbose_name = ('post')
    verbose_name_plural = ('posts')
    ordering  = ('-published',)
    get_latest_by = 'published'

  def __unicode__(self):
    return self.title

Solution

  • I don't think this is causing your error, but you're missing populate_from in your AutoSlugField declaration, and I don't think you need unique=True:

    class Post(models.Model):
    """Blog post model."""
    title = models.CharField('title', max_length=120)
    slug = AutoSlugField('slug', unique=True, max_length=120, primary_key=True)
        ... snip...
    

    I think you want:

    slug = AutoSlugField(populate_from = 'title', max_length=120, primary_key=True)
    

    Or at least, that's how I use AutoSlugField in some of my code.

    I think you're getting your error because django-tagging expects primary keys to be integers, whereas your primary key is going to be a string. Is there a good reason for your primary_key=True declaration? Why not just use the default of the automatically added id column?

    If you're wanting to access your posts using the slug in your URLs (which after all is the point of slugs!), then given this entry in your urls.py:

    url(r'post/(?P<slug>.+)/$', single_post)
    

    You want a view like this:

    def single_post(request, slug):
       post = get_object_or_404(Post, slug = slug)
       ...
    

    Or you can use generic views.