Search code examples
pythondjangodjango-admin

Setting initial value for a new foreign key on django admin


I have the following django models:

class ModelA(models.Model):
   something = models.ForeignKey('Something')
   extra_data = models.ForeignKey('ModelB')

class ModelB(models.Model):
   something = models.ForeignKey('Something')

I have registered both models with django admin.

Is is possible to pre-set ModelB's something to the parent's something value when I create a new Model B via the + button?

enter image description here

I have tried using formfield_for_foreignkey and setting kwargs["initial"] but that only is able to set the foreign key itself, it does not provide default values for new objects.

This should be possible to do by making the + link URL to add &something= to the current object's something value. But I am not sure how to tell django to do this.


Solution

  • I was able to get around it by adding custom JS in the admin webpage.

    class ModelA_Admin(admin.ModelAdmin):
        model = ModelA
        class Media:
            js = ('admin/js/mycustomscript.js',)
    

    In mycustomscript.js:

    • Add a document load event that:
      • Finds the something select html element using the xpath:

        //div[contains(@class, 'field-something')]//select

      • Uses select.value to retrieve the selected something pk

      • Then finds the extra_data's + button using the xpath:

        //div[contains(@class, 'field-extra_data')]//a[contains(@class, 'add-related')]

      • Finally adds the field value via get params into the link:

        a.href += `&something=${selected}`;