[Answered ]-Django Admin: variables/constants inside Django Admin that can be changed

2👍

then do something like:

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()

This way you have only 1 allowed instance for this mode – which can exist of only 1 field that is your constant value.

You can go more save and not only check if your current instance already exists, but check if your current instance is that one instance you may already have.

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

Additionally, if you want to use this constant represented by a model anywhere in your app/project, you simply must provide ForeignKeys from other models to this, where it is necessary.

👤Max M

Leave a comment