Django Admin:如何仅保存内联模型而不保存父模型
我有以下简化的设置:
- 基于无法更改的遗留数据的模型。因此,我提出一个 ValidationError 以使用户意识到没有进行任何更改。表单字段是只读的,我可以使用简单的“pass”,但我更喜欢收到 save() 没有执行其预期操作的消息,而不是默默地不执行任何操作。
- 现在我正在使用第二个模型扩展遗留数据,该模型应该是可编辑的。它作为内联包含在遗留模型的 ModelAdmin 中。我可以将 CommentModel 本身包含为 ModelAdmin,但由于 LegacyModel 从父类继承了许多功能,这会变得复杂且不干燥。
我想要的是仅在内联模型上执行“保存”操作。我认为由于所有字段都是只读的,它应该可以正常工作。有人可以给我一个提示,以干净的方式做到这一点吗?
class Legacy(models.Model):
legacyData = models.TextField()
def clean(self):
raise ValidationError("%s model is readonly." % self._meta.verbose_name.capitalize())
class Comment(models.Model):
legacy = models.OneToOneField(Legacy)
comment = models.TextField()
class LegacyAdmin(admin.ModelAdmin):
def __init__(self, *args, **kwargs):
self.readonly_fields = self.fields
super(LegacyAdmin, self).__init__(*args, **kwargs)
model = Legacy
inlines = (CommentInline, )
非常感谢您抽出时间! :)
I have following simplified setup:
- A model based on legacy data which can't be changed. Therefore I raise a ValidationError to make the user aware that there was no change made. The form fields are readonly and I could use a simple 'pass' but I prefer to get the message that save() didn't do what it was intended to do instead of just do silently nothing.
- Now I'm extending the legacy data with a 2nd model which should be editable. It is included it into the legacy model's ModelAdmin as inline. I could include the CommentModel itself as a ModelAdmin, but as the LegacyModel inherits lots of functionality from parent-classes this gets complicated and un-dry.
What I want is to perform the "save" operation only on the inline-model. I thought as all fields are readonly it should work fine. Can someone give me a hint to do this in clean way?
class Legacy(models.Model):
legacyData = models.TextField()
def clean(self):
raise ValidationError("%s model is readonly." % self._meta.verbose_name.capitalize())
class Comment(models.Model):
legacy = models.OneToOneField(Legacy)
comment = models.TextField()
class LegacyAdmin(admin.ModelAdmin):
def __init__(self, *args, **kwargs):
self.readonly_fields = self.fields
super(LegacyAdmin, self).__init__(*args, **kwargs)
model = Legacy
inlines = (CommentInline, )
Thanks a lot for your time! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以覆盖遗留的 save() 并使用 http://docs.djangoproject.com/en/dev/ref/contrib/messages/ 告诉您的用户没有发生什么。
Rather than raising an exception in clean(), you could override the legacy's save() and use http://docs.djangoproject.com/en/dev/ref/contrib/messages/ to tell your user what didn't happen.