【问题标题】:Prevent shell from saving attribute in Django防止shell在Django中保存属性
【发布时间】:2015-02-13 21:00:34
【问题描述】:

我在模型上有一个属性,我不希望其他开发人员能够进入 Django shell 并进行更改。有人知道怎么做吗?我尝试覆盖该模型上的保存方法,但无法确定该属性是否已更改。

【问题讨论】:

  • 用户如何进入 Django shell?
  • 你说得对,“用户”不能。我应该说另一个开发人员
  • 你能详细说明你想要完成什么吗?其他开发人员也可以通过修改您的代码来撤消您的方法。
  • 如果有人可以访问 django shell,也可以访问数据库配置,所以他可以绕过你的预防。除非您自己制作外壳,否则我认为这是不可能的,django 不能那样工作。

标签: django django-models


【解决方案1】:

嗯,我想出了如何做到这一点。其他开发人员可以随时更改代码,但这会引发错误,说明这不是他们应该做的。

class myModel(models.Model):


    uuid = UUIDField('UUID', primary_key=True, default=uuid4)
    model_type = models.ForeignKey(ModelType)

    # override the Press model __init__ method to store initial press_type
    def __init__(self, *args, **kwargs):
        super(myModel, self).__init__(*args, **kwargs)
        self.__model_type = self.model_type

    # override the save method to prevent updates to press_type
    def save(self, *args, **kwargs):
        # raise an exception if press_type was changed since initialized
        if self.pk and self.__model_type != self.model_type:
            raise Exception('The model_type field cannot be changed once set.')

        super(myModel, self).save(*args, **kwargs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 2017-08-17
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2014-04-18
    • 2014-11-14
    • 2020-08-14
    相关资源
    最近更新 更多