Django Admin:Django Admin中可以更改的变量/常量



我想在 Django Admin 中使用变量/常量,稍后可以在代码中使用。

例如 API 密钥、谷歌跟踪代码管理器识别号等。

我知道我可以在设置或其他文件中设置它们,但这更适合营销团队,可以更改。

如何做到这一点?只是单个记录变量(不是多个 - 所以模型不是最好的解决方案(

然后执行以下操作:

class myConstant(models.Model)
# ...
def clean(self):
if self.id: # instance already exists
# do some clean
elif myConstant.objects.count() > 0:
raise ValidationError("Only one instance allowed")
else:
# do some clean
def save(self):
# check if this instance already exists
if self.id:
super().save()
# else: count numbers of all instances of this model
elif myConstant.objects.all().count() > 0:
return # no save will be processed
else:
super().save()

这样,此模式只有 1 个允许的实例 - 该实例只能存在 1 个字段,即您的常量值。

您可以进行更多保存,不仅可以检查当前实例是否已存在,还可以检查当前实例是否是您可能已经拥有的实例。

if myConstant.objects.count() > 0 and myConstant.objects.all[0] == self:
# do some clean in case of clean() method
super().save() # in case of save method

此外,如果要在应用/项目中的任何位置使用此常量由模型表示,则只需在必要时提供其他模型的外键即可。

最新更新