3

This is my models

from django.db import models

class Page(models.Model):
    page_id = models.IntegerField(default=0)

class Question(models.Model):
    page = models.ForeignKey(Page)
    question = models.CharField(max_length=150)

class Option(models.Model):
    question = models.ForeignKey(Question)
    option = models.CharField(max_length=100)
    image_class = models.CharField(max_length=75)

this is my admin.py

from django.contrib import admin
from .models import Page, Question, Option

class OptionInline(admin.StackedInline):
    model = Option
    extra = 1

class QuestionInline(admin.StackedInline):
    model = Question
    extra = 1
    inlines = [OptionInline]

class PageAdmin(admin.ModelAdmin):
    inlines = [QuestionInline]

admin.site.register(Page, PageAdmin)

basically i want this multi level relation to appear as a multi level inline in the admin site. can someone please help out

Syed Is Saqlain
  • 360
  • 1
  • 3
  • 13
  • Django's admin doesn't support nested inlines so you'll have to write your own `ModelAdmin` and `Inline` subclasses, as well as all the relevant template and javascript code. – bruno desthuilliers Sep 15 '15 at 07:10
  • No answer is accepted yet? Is the question still valid? Did you find any other solution? – raratiru Oct 25 '16 at 14:38

2 Answers2

3

Instead of using nested inlines, Django 1.8 provides the InlineModelAdmin.show_change_link

from django.contrib import admin
from .models import Page, Question, Option

class OptionInline(admin.StackedInline):
    model = Option
    extra = 1

class QuestionInline(admin.StackedInline):
    model = Question
    extra = 1
    show_change_link = True


class PageAdmin(admin.ModelAdmin):
    inlines = [QuestionInline,]

admin.site.register(Page, PageAdmin)


class QuestionAdmin((admin.ModelAdmin):
    inlines = [OptionInline,]

admin.site.register(Question, QuestionAdmin)

This way, when you save the Page model -having completed the inline Question model- a link called 'change' will appear at the saved instance of the inline Question model. Clicking it, you will land at the main page of the Question model instance with the Option model as inline.

When you complete the Option model inline and hit the 'save and continue editing', the back button should return you to the relevant Page instance.

There is also a post which describes how you can achieve the same result if you use previous Django versions.

Community
  • 1
  • 1
raratiru
  • 8,748
  • 4
  • 73
  • 113
1

Django does not support it out of the box, but there is project called django-nested-inline that will do the job. Also you can make your own solution.

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77