Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi level Inlines Django

Tags:

python

django

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

like image 921
Syed Is Saqlain Avatar asked Jul 21 '26 06:07

Syed Is Saqlain


2 Answers

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.

like image 101
raratiru Avatar answered Jul 22 '26 21:07

raratiru


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.

like image 20
GwynBleidD Avatar answered Jul 22 '26 21:07

GwynBleidD