10

My site has few global configurations. For example "smtp-server address", "company address", etc.

Of course I can:

  1. Create variables in settings.py and use it in templates and apps;
  2. Create a model (like Configuration) and write all needed fields there.

If I use the first way I can't give access for changing these fields in django-admin.

If I use the seconds way it is not a beautiful solution, because everywhere in the code I have to use model_name.objects.get(id=1) and I need only one instance. Models were created for other tasks.

How can I solve this problem?

ChrisCrossCrash
  • 651
  • 8
  • 18
SkyFox
  • 1,805
  • 4
  • 22
  • 33
  • 1
    In future, please check the live preview of your post to make sure the formatting will be approximately correct. – David Wolever Mar 25 '12 at 07:57
  • 3
    Using [django-solo](http://stackoverflow.com/a/20813571/1888983) ([github](https://github.com/lazybird/django-solo)) to create a singleton was quite painless for me. – jozxyqk May 09 '15 at 10:00

3 Answers3

7

This is what I did. Might not be the most optimal solution but works for me.

  1. Create a Configuration model and do all the usual stuff as in your point 2. Create a function (say in configuration.view) which will pull out and return the configuration values in a dict.

  2. Now in your settings.py, import your function and set the returned dict to a settings.py variable: CONFIG = configuration.view.get_config()

  3. Create a template context processor which will set this CONFIG dict in the template context.

    def init_site_settings(request):
        return settings.CONFIG
    
  4. Add this context processor to your TEMPLATE_CONTEXT_PROCESSORS

  5. Now you are free to use your configuration parameters in templates as {{my_config_key}}

Hope this helps.

Husain Basrawala
  • 1,757
  • 15
  • 21
4

Have a look at http://www.djangopackages.com/grids/g/live-setting/ from my similar question Changing Django settings at runtime

Regarding the id=1 notation, a) you can define a corresponding attribute on your manager https://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods b) yes that's still a database query - checkout https://github.com/disqus/django-modeldict/ for an approach with lazy access and caching.

Community
  • 1
  • 1
Danny W. Adair
  • 12,498
  • 4
  • 43
  • 49
0

For your option 2, hard-coded id=1 is terrible, use get() directly. Thus you could use:

get_conf = lambda: model_name.objects.get()

Also there are other apps for the requirements, such as http://bitbucket.org/bkroeze/django-livesettings/ . You may want to check.

okm
  • 23,575
  • 5
  • 83
  • 90