0

在打开模型实例的管理页面时,向 a 添加额外的表单字段时readonly_fields出现错误ModelAdminImproperlyConfigured

TaskClosedAdmin.readonly_fields[0], 'extra_admin_field' is not a callable or an attribute of 'TaskClosedAdmin' or found in the model 'TaskClosed'.

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

编辑

我也尝试过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

我仍然收到关于extra_admin_field不存在的相同错误...我在哪里可以添加它?

模型.py

class Task(models.Model):

    # some fields


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

管理员.py

class TaskForm(forms.ModelForm):

    extra_admin_field = forms.CharField(max_length=10)

    class Meta:
        model = Task


    def __init__(self, *args, **kwargs):

        super(TaskForm, self).__init__(*args, **kwargs)

        # set extra_admin_field value


class TaskAdmin(admin.ModelAdmin):

    form = TaskForm


class TaskClosedAdmin(TaskAdmin):

     readonly_fields = ('extra_admin_field',)
4

1 回答 1

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/

于 2013-03-11T19:43:49.207 回答