0

I've been trying to override the functioning of +(add) button for related fields in Django admin to open a new tab instead of a popup. I looked at the RelatedObjectLookup.js to see how it works but still stuck at implementing the same functioning by opening a new tab. Is there any way to implement such a thing or to render the form 'inline'?

ParfectShot
  • 123
  • 2
  • 12
  • Isn't [django forms](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects) is not what you are looking for? Specifically [this](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany) method. – Charnel Jan 27 '20 at 10:02
  • No, I want to open a new tab when '+' is clicked instead of a popup. Everything else is working fine. And this is required because another person working on the same project reported that the popups are by default not opening above the main window, instead they open behind the main window. Could be a browser specific issue but this is what he requested. – ParfectShot Jan 27 '20 at 10:10

1 Answers1

2

To open related fields +Add button in a new tab, you have to set target="_blank" attribute for all those links.

Override admin/change_form.html from your admin.

class BookAdmin(admin.ModelAdmin):
    add_form_template = 'book/admin/change_form.html'

In the html, set the required attribute and remove

{% extends 'admin/change_form.html' %}

{% load static %}


{% block admin_change_form_document_ready %}
    {{ block.super }}

    <script type="text/javascript">
    (function($) {
        $(document).ready(function() {
            classes = document.getElementsByClassName('add-related');
            for (i=0; i<classes.length; i++) {
                // set target to blank
                classes[i].setAttribute('target', '_blank');
                // remove the class to prevent django listeners overriding click on link
                classes[i].classList.remove("related-widget-wrapper-link");
            };

        });
    })(django.jQuery);
    </script>
{% endblock %}

Now when you click on related fields, it will open in a new tab.

An alternate option is to use inline admin as mentioned here in docs.

Chillar Anand
  • 27,936
  • 9
  • 119
  • 136
  • I implemented this using jquery(in my admin.js file) without modifying the change_form HTML and removed 'related-widget-wrapper-link' class. Working great. However, after submitting the form blank white page returned. Now looking for how to fix this(close the tab after submitting). – ParfectShot Feb 10 '20 at 05:37