[Django]-How to add forreign key fields like it happens in django admin site?

3👍

I think you have to create a seperate view to create a DealType.

In your DealForm you add a link to open that view.

I took a look at an admin page from a project of mine.

html

<a href="/admin/portfolio/category/add/" class="add-another" id="add_id_category" onclick="return showAddAnotherPopup(this);"> <img src="/static/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/>    </a>

Javascript

taken from

<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js">  </script> 

function showAddAnotherPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^add_/, '');
    name = id_to_windowname(name);
    href = triggeringLink.href
    if (href.indexOf('?') == -1) {
        href += '?_popup=1';
    } else {
        href  += '&_popup=1';
    }
    var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

This opens a new window with the view with the add form.

This view should add the DealType and then close the window using the following function also found in the same javascript file

function dismissAddAnotherPopup(win, newId, newRepr) {
    // newId and newRepr are expected to have previously been escaped by
    // django.utils.html.escape.
    newId = html_unescape(newId);
    newRepr = html_unescape(newRepr);
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem) {
        if (elem.nodeName == 'SELECT') {
            var o = new Option(newRepr, newId);
            elem.options[elem.options.length] = o;
            o.selected = true;
        } else if (elem.nodeName == 'INPUT') {
            if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                elem.value += ',' + newId;
            } else {
                elem.value = newId;
            }
        }
    } else {
        var toId = name + "_to";
        elem = document.getElementById(toId);
        var o = new Option(newRepr, newId);
        SelectBox.add_to_cache(toId, o);
        SelectBox.redisplay(toId);
    }
    win.close();
}

This is just backtracked from the admin panel but it should get you started.

Found a guide that walks you through the process here which probably explains alot better. (havn’t read it)

Leave a comment