如何在Django admin中的字段旁边添加自定义按钮?

如何在Django admin中的字段旁边添加自定义按钮?,django,django-forms,django-templates,django-admin,Django,Django Forms,Django Templates,Django Admin,我有一个客户端模型,其中包括一个用于客户端API密钥的字段 在Django Admin中添加新客户机时,我希望在API字段旁边有一个按钮来生成新密钥(我有这个方法)。一旦生成,该字段将用密钥更新 如何在字段旁边添加此按钮?我应该使用自定义小部件吗?在我的例子中,我正在使用我创建的按钮进行API调用,因此我也将介绍我是如何做到这一点的。当然,你的按钮可以做任何你喜欢的事情 首先,在模型中创建一个输出按钮的函数。我将使用我的示例,即models.py: class YourModel(models.

我有一个客户端模型,其中包括一个用于客户端API密钥的字段

在Django Admin中添加新客户机时,我希望在API字段旁边有一个按钮来生成新密钥(我有这个方法)。一旦生成,该字段将用密钥更新


如何在字段旁边添加此按钮?我应该使用自定义小部件吗?

在我的例子中,我正在使用我创建的按钮进行API调用,因此我也将介绍我是如何做到这一点的。当然,你的按钮可以做任何你喜欢的事情

首先,在模型中创建一个输出按钮的函数。我将使用我的示例,即models.py:

class YourModel(models.Model):

    ....

    def admin_unit_details(self):  # Button for admin to get to API
        return format_html(u'<a href="#" onclick="return false;" class="button" '
                           u'id="id_admin_unit_selected">Unit Details</a>')
    admin_unit_details.allow_tags = True
    admin_unit_details.short_description = "Unit Details"
我还想指出,我通过表单传递了API地址和头,但是您可以在代码中使用正确的头/密码。我只是将我的所有文件保存在一个位置(settings.py)、forms.py(可选):

最后看一下我的js,正如我的admin Media类所引用的,它位于admin_custom/js/myjs.js中:

这类似于添加管理员映像,请参阅。另外,在此搜索allow_tags属性,它显示了一个很好的示例

// Make sure jQuery (django admin) is available, use admin jQuery instance
if (typeof jQuery === 'undefined') {
    var jQuery = django.jQuery;
}

var unit_information = {};

jQuery( document ).ready(function() {

    jQuery('#id_admin_unit_selected').click( function() {

        //get the data from id_selected_unit, from the api_header api_address attributes
        var unit_select = jQuery('#id_selected_unit');
        var header = unit_select.attr('api_header');
        var address = unit_select.attr('api_address');
        var selected_unit = unit_select.val();

        if (header && address && selected_unit){
            var unit_address = address + '/units/' + selected_unit
            get_unit(header, unit_address)
        }
        else{
            // if can't connect to api, so hide
            jQuery('.field-admin_unit_details').hide();
        }

    });

});


function get_unit(header, address){

    jQuery.ajax
    ({
        type: "GET",
        url: address,
        dataType: 'json',
        headers: {
        "Authorization": header
        },
        success: function (result) {
            //TODO: output this in a modal & style
            unit_information = JSON.stringify(result);
            alert(unit_information)
        },
        error: function(xhr, textStatus, errorThrown) {
            alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
        }
    });

}
这将在警报中输出,您还可以将其记录到控制台或为其定义自己的模式/样式


希望这有帮助,干杯

从您添加到这个问题的不同标签来看,信息太少,无法认真回答。您可以使用ovveride djangos管理模板并使用自己的模板。本文可能有助于找到正确的方向:注意:按钮必须列为只读字段,否则将抛出错误。我简化了这个(没有额外的JS和CSS),它对我来说很有用。我把输出按钮的函数移到了管理文件中,这样就不会把我的模型弄得乱七八糟。另外,
allow_标签
不再需要!
from settings import API_ADDRESS, API_HEADER
class MyModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(WorksheetForm, self).__init__(*args, **kwargs)

        self.fields['selected_unit'].widget = forms.Select(choices=get_worksheet_unit_choice_list(self.instance.id),
                                                           attrs={'api_address': API_ADDRESS, 'api_header': API_HEADER})

    ....
// Make sure jQuery (django admin) is available, use admin jQuery instance
if (typeof jQuery === 'undefined') {
    var jQuery = django.jQuery;
}

var unit_information = {};

jQuery( document ).ready(function() {

    jQuery('#id_admin_unit_selected').click( function() {

        //get the data from id_selected_unit, from the api_header api_address attributes
        var unit_select = jQuery('#id_selected_unit');
        var header = unit_select.attr('api_header');
        var address = unit_select.attr('api_address');
        var selected_unit = unit_select.val();

        if (header && address && selected_unit){
            var unit_address = address + '/units/' + selected_unit
            get_unit(header, unit_address)
        }
        else{
            // if can't connect to api, so hide
            jQuery('.field-admin_unit_details').hide();
        }

    });

});


function get_unit(header, address){

    jQuery.ajax
    ({
        type: "GET",
        url: address,
        dataType: 'json',
        headers: {
        "Authorization": header
        },
        success: function (result) {
            //TODO: output this in a modal & style
            unit_information = JSON.stringify(result);
            alert(unit_information)
        },
        error: function(xhr, textStatus, errorThrown) {
            alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
        }
    });

}