Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 544
valignatev Avatar asked Nov 17 '15 02:11

valignatev


People also ask

What is Django admin inline?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.

How do I automatically register all models in Django admin?

To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it. This will fetch all the models in all apps and registers them with the admin interface.


2 Answers

do something like this:

class ChannelAdmin(admin.TabularInline):
    model = Channel

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

admin.site.register(Rule,RuleAdmin)
like image 158
bakarin Avatar answered Oct 01 '22 22:10

bakarin


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

class OrderAdmin(admin.ModelAdmin):
    list_display = ['id']
    list_filter = ['status']
    inlines = [OrderItemInline]
like image 36
Alex Karahanidi Avatar answered Oct 01 '22 23:10

Alex Karahanidi