django settings per application - best practice?

后端 未结 4 499
忘了有多久
忘了有多久 2021-02-01 12:58

this is somewhat related to this question
Why is django's settings object a LazyObject?

In my django project i have several applications. Each application can ha

4条回答
  •  悲哀的现实
    2021-02-01 14:02

    The simplest solution is to use the getattr(settings, 'MY_SETTING', 'my_default') trick that you mention youself. It can become a bit tedious to have to do this in multiple places, though.

    Extra recommendation: use a per-app prefix like MYAPP_MY_SETTING.

    There is a django app, however, that gets rid of the getattr and that handles the prefix for you. See http://django-appconf.readthedocs.org/en/latest/

    Normally you create a conf.py per app with contents like this:

    from django.conf import settings
    from appconf import AppConf
    
    class MyAppConf(AppConf):
        SETTING_1 = "one"
        SETTING_2 = (
            "two",
        )
    

    And in your code:

    from myapp.conf import settings
    
    def my_view(request):
        return settings.MYAPP_SETTINGS_1  # Note the handy prefix
    

    Should you need to customize the setting in your site, a regular entry in your site's settings.py is all you need to do:

    MYAPP_SETTINGS_1 = "four, four I say"
    

提交回复
热议问题