这是我的模型
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 []
但现在,如果用户添加新注释,他会看到禁用(不可编辑)的注释文本区域。但是用户可以看到旧字段不可编辑。
如何实现这个功能呢?
我也有同样的询问。
但是,我不在乎内联中的字段是否是“只读”。我只是不希望它们在创建后被更改。
为此,我创建了一个NoteForm
在 forms.py 中,如果实例在具有初始数据时发生更改,则会引发验证错误:
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__'
管理员.py:
class NoteInline(GenericTabularInline):
model = Note
extra = 0
form = NoteForm
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)