Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7596745
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T21:59:34+00:00 2026-05-30T21:59:34+00:00

I have some Django models with a structure similar to this: class Grandparent(models.Model): name

  • 0

I have some Django models with a structure similar to this:

class Grandparent(models.Model):
    name = models.CharField(max_length=80)

class Parent(models.Model):
    name = models.CharField(max_length=80)
    grandparent = models.ForeignKey(Grandparent, related_name='children')

class Child(models.Model):
    parent = models.ForeignKey(Parent, related_name='children')

class ChildA(Child)
    something = models.CharField(max_length=80)
    anotherthing = models.IntegerField()

class ChildB(Child)
    anything = models.CharField(max_length=80)
    hello = models.BooleanField()

So basically, there are two kind of children which inherit from a practically abstract Child model. (It is not really abstract so I could use a foreign key with it).

The question is – how will I be able to create a link from the admin page of the first model (Grandparent) to the creation page of a new Parent model?
That Parent model needs to already have the Grandparent foreign key field populated by the currently viewed grandparent page id.

Inlines are the thing that comes to mind, but I will not be able to use them because inlines cannot be nested and I will be needing them to manipulate the fields inside ChildA and ChildB on the Parent page.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T21:59:35+00:00Added an answer on May 30, 2026 at 9:59 pm

    The answer consists of two steps:

    # your_app_name/admin.py    
    from django import forms
    from django.utils.safestring import mark_safe
    from django.contrib import admin
    from django.core.exceptions import ObjectDoesNotExist
    
    # 1. Override `Grandparent`'s and `Parent`'s `ModelAdmin` forms:
    #
    # Create a widget with a hyperlink to `Parent` admin form
    # with `Grandparent`'s primary key as `GET` parameter.
    # Place it in `Grandparent`'s `ModelAdmin`:
    
    class AddParentAdminWidget(forms.Widget):
    
        def __init__(self, obj, attrs=None):
            self.object = obj
            super(AddParentAdminWidget, self).__init__(attrs)
    
        def render(self, name, value, attrs=None):
            if self.object.pk:
                return mark_safe(
                    u"""<a class="button" href="../../../%(app_label)s/%(object_name)s/add/?grandparent_pk=%(object_pk)s">%(linktitle)s</a>
                    """ %\
                    {
                        'app_label': Parent._meta.app_label,
                        'object_name': Parent._meta.object_name.lower(),
                        'object_pk': self.object.pk,
                        'linktitle': 'Add new Parent instance with prepopulated Grandparent field.',
                        }
                )
            else:
                return mark_safe(u'')
    
    # Add a dummy `add_new_parent_link` field to `Grandparent's` form
    # just to be able to replace it with your previously created widget.
    
    class GrandparentAdminForm(forms.ModelForm):
        add_new_parent_link = forms.CharField(label = 'Add new parent instance', required = False)
    
        def __init__(self, *args, **kwargs):
            super(GrandparentAdminForm, self).__init__(*args, **kwargs)
            # instance is always available, it just does or doesn't have pk.
            self.fields['add_new_parent_link'].widget = AddParentAdminWidget(self.instance)
    
        class Meta:
            model = Grandparent
    
    class GrandparentAdmin(admin.ModelAdmin):
        form = GrandparentAdminForm
    
    # 2. Set initial data in `Parent`'s `ModelForm`
    #
    # (do this by accessing the `request` object,
    # which is set in `ParentAdmin` code below):
    
    class ParentAdminForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            self.request = kwargs.pop('request', None)
            super(ParentAdminForm, self).__init__(*args, **kwargs)
            if self.request.GET.get('grandparent_pk', False):
                try:
                    grandparent_pk = int(self.request.GET.get('grandparent_pk', ''),)
                except ValueError:
                    pass
                else:
                    try:
                        Grandparent.objects.get(pk = grandparent_pk)
                    except ObjectDoesNotExist:
                        pass
                    else:
                        self.initial['grandparent'] = grandparent_pk
    
        class Meta:
            model = Parent
    
    # Add your children as regular `StackedInline`'s
    
    class ChildInline(admin.StackedInline):
        model = Child
    
    class ChildAInline(admin.StackedInline):
        model = ChildA
    
    class ChildBInline(admin.StackedInline):
        model = ChildB
    
    class ParentAdmin(admin.ModelAdmin):
        form = ParentAdminForm
    
        def get_form(self, request, obj=None, **kwargs):
            """
            Use a trick to be able to access `request` object in `ParentAdminForm`.
            Yes, unfortunately we need it [http://stackoverflow.com/a/6062628/497056]
            to access `request` object in an admin `ModelForm` (as of `Django` 1.4).
            Hopefully, this will be fixed in newer versions.
            """
            AdminForm = super(ParentAdmin, self).get_form(request, obj, **kwargs)
            class ModelFormMetaClass(AdminForm):
                """
                We need this metaclass
                to be able to access request in a form
                """
                def __new__(cls, *args, **kwargs):
                    kwargs['request'] = request
                    return AdminForm(*args, **kwargs)
    
            return ModelFormMetaClass
    
        inlines = [
            ChildInline,
            ChildAInline,
            ChildBInline,
            ]
    
    admin.site.register(Grandparent, GrandparentAdmin)
    admin.site.register(Parent, ParentAdmin)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

If you have some models: class Teacher(models.Model): name = models.CharField(max_length=50) class Student(models.Model): age =
So I have some Django 1.3 models like this: class Type(models.Model): is_bulk = models.BooleanField()
I have some simple Django Models like this: class Event(models.Model): # some stuff class
Say I have some django models, something like this: class Address(models.Model): pass class Person(models.Model):
I have an extended UserProfile model in django: class UserProfile(models.Model): user = models.ForeignKey(User, unique=True)
I'm working on some Django-code that has a model like this: class Status(models.Model): code
Given the Django models: class ContainerOwner(models.Model): id = models.IntegerField() class Container(models.Model): owner = models.ForeignKey(ContainerOwner)
today a weird problem occurred to me: I have a model class in Django
I have some django apps which are versioned by app name. appv1 appv2 The
I have a situation like this: there are three Django models, let's call them

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.