Django admin with inlines, 1 model with 2 foreigns keys to 2 different models

56 views Asked by At

I have 3 models total. My main model has 2 foreign keys to 2 different models. So the relationships are setup as a many-to-one. When I try to customize the admin, I cannot get it to simply allow me to edit the main character model and have the 2 inlines (universe and series) show up.

What is the simplest way? There seams to be some ambiguity since the 2 foreign fields are throwing everything off. I have scoured the documentation but I must have missed something; I have gotten a more complex many-to-many working in the admin, so this is a bit odd.

Here are my models:

class CharacterSeries(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name


class CharacterUniverse(models.Model):
    name = models.CharField(max_length=200) 

    def __unicode__(self):
        return self.name


class Character(models.Model):
    name = models.CharField(max_length=200) 
    rating = models.DecimalField(max_digits=3, decimal_places=1)
    universe = models.ForeignKey(CharacterUniverse)    
    series = models.ForeignKey(CharacterSeries)

    def __unicode__(self):
        return self.name

Here is my admin:

from django.contrib import admin
from .models import Character, CharacterUniverse, CharacterSeries

# Register your models here.


class SeriesInline(admin.TabularInline):
    model = Character

class UniverseInline(admin.TabularInline):
    model = Character

class Characterdmin(admin.ModelAdmin):
    inlines = [
        UniverseInline,
        SeriesInline,
   ]

admin.site.register(Character, CharacterAdmin)   
1

There are 1 answers

11
xyres On BEST ANSWER

Update

The code I posted earlier was wrong! I didn't read your models too carefully. Sorry about that.

If you want to create CharacterSeries and CharacterUniverse while you create/edit the Character, you could do this:

from django.contrib import admin
from .models import Character, CharacterUniverse, CharacterSeries

# No need to define `ModelAdmin` classes

admin.site.register(Character)
admin.site.register(CharacterUniverse)
admin.site.register(CharacterSeries)

The code above will give you a + (plus) sign after the universe and series fields. This will help you create CharacterUniverse and CharacterSeries objects on the fly.