2
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.

Community
  • 1
  • 1
the_unknown_spirit
  • 2,518
  • 7
  • 34
  • 56
  • Can you please explain why you think this is not ' a sound way' to do this? Isnt this approach more readable than accessing a constant? – Aswin P J Apr 09 '16 at 09:01
  • Hardcoding things is not a correct way. This may not be the only instance where i need it. If I keep things hardcoded , in case I want to change that hardcoded value I will have to change from every instance which maynot be feasible if I am working with lots of such instances. – the_unknown_spirit Apr 09 '16 at 09:25
  • How about this approach https://gist.github.com/aswinpj/baf79d2f1ff212b8552d7164ce1bd5a5 – Aswin P J Apr 09 '16 at 09:31

3 Answers3

6

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.

Ben
  • 6,687
  • 2
  • 33
  • 46
1

You can store constants in a seperate file and import it into your project

folder/

appconfigurations.py
views.py

appconfigurations.py

YOUR_CONSTANT = "constant_value"

views.py

from appconfigurations import *

def your_view(request):
    constant = YOUR_CONSTANT
jithin
  • 1,412
  • 2
  • 17
  • 27
0

In views.py file:

from django.conf import settings
settings.Variable_Name
Walk
  • 1,531
  • 17
  • 21