Search code examples
djangoforeign-keysslug

Prepopulate slug field from Foreign Key in Django


How would I go about prepopulating a slug from a foreign key? Here are how some of my models are setup:

Class Title(models.Model):
    title = models.CharField(max_length=256)
    slug = models.SlugField() 

class Issue(models.Model):
    title = models.ForeignKey(Title)
    number = models.IntegerField(help_text="Do not include the '#'.")
    slug = models.SlugField()

admin.py:

class IssueAdmin (admin.ModelAdmin):      
    prepopulated_fields = {"slug": ("title",)}    
admin.site.register(Issue, IssueAdmin)

What the Issue prepopulates is the ID of the foreign key, but I suppose I would need it to preopulate the slug of the foreign key. How would I go about doing this? I am using Django 1.3. I have checked other threads, but they seem to refer to version of Django a few years older that don't work anymore.

I need the Titles to display the list of issues. So far, it works. And you can click on the link to the issue to see what the issue displays.

I feel as if reworking the Title to abstract classes the way Skidoosh will not allow me to view subsets of objects....


Solution

  • If you check the docs (http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields) it does state that you can't reference a foreign key field.

    Looking at you design would this not work better:

    class BaseModel(models.Model):
        title = models.CharField(max_length=256)
        slug = models.SlugField()
    
    class Issue(BaseModel):
        number = models.IntegerField(help_text="Do not include the '#'.")
    
    class ComicBookSeries(BaseModel):
        issues = models.ForeignKey(Issue)
    

    You need to declare the classes in that order!

    Hope that helps!