Site configuration in django-admin

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

Of course I can:

  • Create variables in settings.py and use them in templates and applications;
  • Create a model (for example, Configuration ) and write all the necessary fields there.

If I use the first method, I cannot give access to change these fields in django-admin.

If I use seconds, this is not a beautiful solution, because everywhere in the code I will 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?

+8
python django django-admin
source share
3 answers

This is what I did. This may not be the best solution, but it works for me.

  • Create a configuration model and do the usual thing, as at your point 2. Create a function (say, in configuration.view ) that pulls out and returns the configuration values ​​to the dict.

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

  • Create a template context handler that sets this CONFIG dict in the template context.

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

  • Now you can use your configuration options in templates as {{my_config_key}}

Hope this helps.

+6
source share

See http://www.djangopackages.com/grids/g/live-setting/ from my similar question Changing Django Settings at Runtime

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

+2
source share

For your option 2, the hard code id = 1 is terrible, use get () directly. So you can use:

 get_conf = lambda: model_name.objects.get() 

There are also other requirements applications, such as http://bitbucket.org/bkroeze/django-livesettings/ . You can check.

0
source share

All Articles