Django Admin:如何仅保存内联模型而不保存父模型

发布于 2024-11-02 03:31:08 字数 950 浏览 5 评论 0原文

我有以下简化的设置:

  • 基于无法更改的遗留数据的模型。因此,我提出一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流绪微梦 2024-11-09 03:31:08

您可以覆盖遗留的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文