【问题标题】:Can't edit but can add new inline in Django admin无法编辑,但可以在 Django admin 中添加新的内联
【发布时间】:2017-08-09 14:09:29
【问题描述】:

这是我的模型

class Note():
    note = models.TextField(null=False, blank=False, editable=True)
    user = models.ForeignKey(to=User, null=True, blank=True)

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey("content_type", "object_id")

下面是我创建此模型以合并到任何管理员中的内联

class NoteInline(GenericTabularInline):
    model = Note
    extra = 0

我需要的是,我想查看所有当前的笔记,但不希望登录的用户编辑它们。目前用户可以编辑旧的和添加新的。所以这就是我所做的,

class NoteInline(GenericTabularInline):
    model = Note
    extra = 0

    def get_readonly_fields(self, request, obj=None):
        if obj and 'change' in request.resolver_match.url_name:
            return ['note', 'user', ]
        else:
            return []

但是现在如果用户添加新笔记,他会看到一个禁用(不可编辑)的笔记文本。但是用户可以看到旧字段不可编辑。

如何实现这个功能?

【问题讨论】:

标签: python django


【解决方案1】:

我也有同样的询问。

但是,我不在乎内联中的字段是否“只读”。我只是不希望它们在创建后更改。

为此,我在 forms.py 中创建了一个NoteForm,如果实例在具有初始数据时发生更改,则会引发验证错误:

class NoteForm(forms.ModelForm):
    def clean(self):
        if self.has_changed() and self.initial:
            raise ValidationError(
                'You cannot change this inline',
                code='Forbidden'
            )
        return super().clean()

    class Meta(object):
        model = Note
        fields='__all__'

admin.py:

class NoteInline(GenericTabularInline):
    model = Note
    extra = 0
    form = NoteForm

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 2013-09-03
    • 1970-01-01
    • 2015-03-20
    • 2012-08-10
    • 1970-01-01
    • 2011-07-30
    • 2011-07-05
    • 2010-10-05
    相关资源
    最近更新 更多