Search code examples
pythondjangodjango-settings

add variables in settings to be used in views - Django


def get(self , request , format=None):
    body = request.data
    name = body.get('name',"The_Flash")

In this instance I have hardcoded the value The_Flash if the request.data receives no value for name , but I know this is not a sound way. I want this to be added as a variable in the settings.py file of my django project. I went through references from SO like this and few others but this is not what I want. Can someone tell me which is the most robust way of doing this. I am using Django 1.8.


Solution

  • We tend to store settings variables in a module in the app called app_settings.py, and use this to set defaults for settings and allow the user to override them in Django's settings.py:

    # app_settings.py
    from django.conf import settings
    
    MY_SETTING = getattr(settings, 'APP_NAME_MY_SETTING', 'the_default_value')
    

    Then import this in your views and use it:

    # views.py
    from app_settings import MY_SETTING
    

    And users can override it in their project settings:

    # project's settings.py
    APP_NAME_MY_SETTING = 'something else'
    

    This allows you to change it per deployment, etc.