Inline in Django admin: doesn't have ForeignKey

I have two Django models:

class Author(models.Model):
    django_login = models.OneToOneField(User, null=True, blank=True)
    user_nicename = models.CharField(max_length=60, blank=True)
    user_url = models.CharField(max_length=100, blank=True)
    user_email =  models.CharField(max_length=100, blank=True)
    display_name =  models.CharField(max_length=250)
    note = models.TextField(verbose_name='O autorze')
    def __unicode__(self):
        return self.display_name

class Photo(models.Model):
    item = models.ForeignKey(Author)
    image = ThumbnailImageField(upload_to='photos')
    caption = models.CharField(max_length=250, blank=True, verbose_name = u"Podpis")
    def __unicode__(self):
        return self.caption

To get inline photos, I have admin.py:

class PhotoInline(admin.StackedInline):
    model = Author

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

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

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

Why?

+4
source share
2 answers

The inline model must have a ForeignKey value for the parent model. To get Photohow inline in Author, your model 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]

More details here .

+6
source

This is because it Authordoes not have a foreign key for the photograph. I think you need to switch the model for inline as follows:

class PhotoInline(admin.StackedInline):
    model = Photo

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

Source: https://habr.com/ru/post/1527830/


All Articles