Python Can';无法编辑,但可以在Django admin中添加新的内联
这是我的模型Python Can';无法编辑,但可以在Django admin中添加新的内联,python,django,Python,Django,这是我的模型 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.
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 []
但现在,若用户添加了新注释,他会看到一个禁用(不可编辑)的注释文本区域。但是,用户可以看到不可编辑的旧字段
如何实现此功能?我也有同样的疑问 但是,我不在乎内联中的字段是否为“只读”。我只是不希望它们一旦被创建就改变 为此,我在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
也许类似的东西可以工作,为“添加”和“更改”视图添加不同的内联视图?这不会使内联部分为只读和部分可编辑(内联注释的新添加)。这就是我所做的,分成两条新的内联线。这里解释得很好