如何在readonly_fields中添加一个modeladmin额外表单字段?

时间:2013-03-11 17:30:33

标签: django admin

readonly_fields的{​​{1}}添加额外的表单字段时,在打开模型实例的管理页面时出现ModelAdmin错误:

ImproperlyConfigured

如何将额外字段添加到readonly_fields?

修改

我还尝试TaskClosedAdmin.readonly_fields[0], 'extra_admin_field' is not a callable or an attribute of 'TaskClosedAdmin' or found in the model 'TaskClosed'. get_form(),认为字段可能会在TaskClosedAdmin之后更新:

super(TaskClosedAdmin, self).get_form(request, obj, **kwargs)

我仍然得到关于def get_form(self, request, obj=None, **kwargs): form = super(TaskClosedAdmin, self).get_form(request, obj, **kwargs) self.readonly_fields = obj._meta.get_all_field_names() self.readonly_fields.append('extra_admin_field') return form 不存在的相同错误...我可以在哪里添加它?

models.py

extra_admin_field

admin.py

class Task(models.Model):

    # some fields


class TaskToConfirm(Task):
    class Meta:
        proxy = True

1 个答案:

答案 0 :(得分:1)

您需要做的是编写一个只读窗口小部件并直接在窗体上指定它,如下所示:

from ... import ReadOnlyWidget

class TaskForm(forms.ModelForm):
    extra_admin_field = forms.CharField(max_length=10)

    class Meta:
        model = Task
        widgets = {
            'extra_admin_field': ReadOnlyWidget,
        }

    def __init__(self, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        # set extra_admin_field value

这里有一个只读小工具(我还没试过):http://djangosnippets.org/snippets/1682/