LarsVegas
LarsVegas

Reputation: 6832

Why doesn't my save method work in the admin?

In my model I overwrite the save-method for my blog model to auto-populate the slug field using the slugify method.

class BlogPost(models.Model):
    title = models.CharField(max_length=100,unique=True)
    slug = models.SlugField(max_length=100,unique=True)
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(Author)
    body = models.TextField()
    category = models.ForeignKey(BlogCategory)

    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.slug = slugify(self.title)

        super(BlogPost, self).save(*args, **kwargs)

But creating a new object in the admin interface doesn't work without either setting the slug field manually or doing something like

class BlogPostAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

Basically I currently have the same functionality defined twice. Any ideas on how to avoid this? And: why doesn't work my own save method in the admin?

Upvotes: 0

Views: 228

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

You should put blank=True in the definition of the slug field.

Upvotes: 3

Related Questions