pythondjangodjango-formsdjango-admindjango-related-manager

Overriding Django Admin's "add" button for related fields


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'?


Solution

  • 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.