Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline in Django admin: has no ForeignKey

Tags:

python

django

I have two Django models:

class Author(models.Model):
    user_email =  models.CharField(max_length=100, blank=True)
    display_name =  models.CharField(max_length=250)

class Photo(models.Model):
    author = models.ForeignKey(Author)
    image = ThumbnailImageField(upload_to='photos')

To get inline photos, I have in admin.py:

class PhotoInline(admin.StackedInline):
    model = Author

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('display_name','user_email')
    inlines = [PhotoInline]

I get an error: Exception at /admin/metainf/author/11/

<class 'metainf.models.Author'> has no ForeignKey to <class 'metainf.models.Author'>

Why?

like image 977
user2140513 Avatar asked Feb 20 '14 06:02

user2140513


3 Answers

The inline model should be having a ForeignKey to the parent model. To get Photo as inline in Author your models code is fine. But your admin code should be as follows:

class PhotoInline(admin.StackedInline):
    model = Photo

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('display_name','user_email')
    inlines = [PhotoInline]

Read more info here.

like image 64
arulmr Avatar answered Nov 06 '22 17:11

arulmr


That's because Author doesn't have a foreign key to photo. I think you need to switch the model for the inline like this:

class PhotoInline(admin.StackedInline):
    model = Photo

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('display_name','user_email')
    inlines = [PhotoInline]
like image 37
bnjmn Avatar answered Nov 06 '22 19:11

bnjmn


Maybe you need to install django-nested-admin library, and later try with NestedStackedInline. django-nested-admin

like image 1
nativelectronic Avatar answered Nov 06 '22 17:11

nativelectronic