Ross Patterson
Ross Patterson

Reputation: 5742

Change Django slug for an existing object?

How does one change the slug for an existing object? I have two objects with conflicting slugs and I need to change one to fix the problem. Is there a way to do this in the admin interface? I'm not seeing one.

Upvotes: 0

Views: 1096

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53999

You need to make sure that a) The appropriate app is registered to appear in the admin interface, and b), the slug is set to be included. In admin.py of the relevant app, you need to make sure that slug is in the fields attribute:

admin.py

class MyModelAdmin(admin.ModelAdmin):
    fields = ( ... , 'slug', ... )
admin.site.register(MyModel, MyModelAdmin)

furthremore, you should try to avoid getting into a situation where two records have the same slug. You can do this by adding unique=True to the model field.

models.py

class MyModel(models.Model):
    ...
    slug = models.CharField(max_length=128, unique=True)

If there are problems with the above, you will have to manually change one of the slugs in the DB or use the shell:

> manage.py shell
> from myapp.models import MyModel
> obj = MyModel.objects.get(id=0) # or whatever the id is for the problematic obj
> obj.slug = "new-slug"
> obj.save()

Upvotes: 2

Related Questions