Cato Johnston
Cato Johnston

Reputation: 45659

How would you populate a field based on another field

From the admin panel I want to populate a slug field based on a certain text field

eg.

Title: My Awesome Page

would automaticaly populate

Slug: my_awesome_page

Upvotes: 4

Views: 3181

Answers (2)

Rasmus Kaj
Rasmus Kaj

Reputation: 4360

There is also an app called django-autoslug which provides a field type AutoSlugField. Using that, you could have:

class Something(models.Model):
    title = models.CharField(max_lenght=200)
    slug = AutoSlugField(populate_from='title')
    ...

This AutoSlugField has many nice features, such as generating a slug so that it is unique either globally of combined with some other field (maybe a category or the year part of a DateTimeField).

See http://pypi.python.org/pypi/django-autoslug for further details.

Upvotes: 1

rz.
rz.

Reputation: 20037

There used to be a prepoulate_from option for the SlugField up to 0.96. It became an admin option after that. See here for reference on that.

Alternatively, you could override the model's save method to calculate the value of the slug field on save().

This question may be helpful, too.

Upvotes: 5

Related Questions