what is the best way to manage this? Thank You in advance for reaching out and trying to help.
CodePudding user response:
It can be easily done via context_processor
, bit of logic and SingleInstanceMixin
class:
class SingleInstanceMixin(object):
"""Makes sure that no more than one instance of a given model is created."""
def clean(self): # noqa: D102
model = self.__class__
if model.objects.exists() and self.id != model.objects.get().id:
raise ValidationError(
_('Only one object of {0} can be created').format(model.__name__),
)
super().clean()
The mixin above you can paste into views.py
or mixins.py
file. Then, you create Settings
model in models.py
file:
class Settings(SingleInstanceMixin, models.Model):
font_name = models.CharField(_('Font name'), max_length=255)
color = models.CharField(_('Color'), max_length=8)
theme_name = models.CharField(_('Theme name'), max_length=64)
def __str__(self):
return _('Settings instance')
You can create also function that creates Settings object when it's needed and populates it with default values:
def get_settings():
return Settings.objects.get_or_create()[0]
(You must define default values in Settings model then).
After all, you pass Settings
instance to context_processors.py
def website(request):
return {
'settings': get_settings(),
}
Rest of logic you need to write yourself, in views, templates etc. But the initial idea how todo that is shown in code I posted here.