'Add inline model to django admin site

I have these two models:

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

class Channel(models.Model):

    id = models.CharField(max_length=9, primary_key=True)
    name = models.CharField(max_length=100)
    rule = models.ForeignKey(Rule, related_name='channels', blank=True)

And I have to be able to add channels to rule in admin site within RuleAdmin interface. So I created these two admin models:

class ChannelAdmin(admin.TabularInline):
    model = Channel

class RuleAdmin(admin.ModelAdmin):
    model = Rule
    inlines = [ChannelAdmin]

But when I start my server I got this errors:

ERRORS:
<class 'main.admin.ChannelAdmin'>: (admin.E202) 'main.Channel' has no ForeignKey to 'main.Channel'.

Still in django shell I can make queries like

rule = Rule.objects.get(pk=1)
rule.channels.all()

There is got to be something obvious but I just can't figure it out.



Solution 1:[1]

do something like this:

class ChannelAdmin(admin.TabularInline):
    model = Channel

class RuleAdmin(admin.ModelAdmin):
   inlines = [ChannelAdmin,]

admin.site.register(Rule,RuleAdmin)

Solution 2:[2]

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    fields = ['image']    

class OrderAdmin(admin.ModelAdmin):
    list_display = ['id']
    list_filter = ['status']
    inlines = [OrderItemInline]

Solution 3:[3]

ADD in admin.py

from .models import Post, Comment

class CommentInline(admin.StackedInline):
    model = Comment
    extra = 0

class PostAdmin(admin.ModelAdmin):
    inlines = [
        CommentInline,
    ]

admin.site.register(Post, PostAdmin)

Click on this: result

Solution 4:[4]

Mar, 2022 Update:

This will work:

from django.contrib import admin
from .models import Channel, Rule

class ChannelInline(admin.TabularInline):
    model = Channel

@admin.register(Rule)
class RuleAdmin(admin.ModelAdmin):
    inlines = [ChannelInline]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alex Karahanidi
Solution 3
Solution 4 Kai - Kazuya Ito