T
T
thebigbang2020-03-09 18:54:08
Django
thebigbang, 2020-03-09 18:54:08

How to change simple data in Django?

I know how to display complex data structures - we create a model, write it to the database via ORM and register it in the admin panel.
But how to add simple data to the admin panel? For example, to be able to manage data in the header of the site - phone, contacts, etc.
You can, of course, create a ContactInfo model, but then the ability to create multiple instances of this class will be superfluous.
I would like the admin panel to have several inputs that directly change the data on the site page.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Serg Syuzev, 2020-03-09
@ssyuzev

from django.db import models


class SingletonModel(models.Model):
    """Singleton model for global settings for example."""

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        """Save with id=1."""
        self.pk = 1
        super(SingletonModel, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        """Can't delete by default."""
        pass

    @classmethod
    def load(cls):
        """Load value from model."""
        obj, created = cls.objects.get_or_create(pk=1)
        return obj

and inherit your model from this one. You also need to add caching - so as not to pull the phone from the database every time

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question