Aman Gupta
Aman Gupta

Reputation: 1874

How to define Constants in settings.py and access them in views function in django

I want to know how can i define some constants in django and use them in view.py function. I have some variables which are never going to be changed and are used in a function many a time. So i decided to define them as constants.

If any one can help me with the declaration of constants and how to import and use them in a function in views.py

EDIT:

constant.py

total_range='A1:C15'

view.py

from constant import *
def myFunction():
    ***Code to access google spreadsheet**
    cell_value_list=worksheet.range(total_range)

here it gives me an error saying total_range is not defined.

Upvotes: 6

Views: 8880

Answers (2)

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

Define a variable like this i settings.py:

MY_VAR = "MY_VALUE"

Import settings in views.py:

from django.conf import settings

You can use your variable in views.py like this:

settings.MY_VAR

You can make a seprate file beside views.py and define all constants on it.

for example create constants.py like this:

const1 = 'value1'
const2 = 'value2'
.
.
.

Now you can use constants in views.py like this:

from constants import *

print const1

Upvotes: 18

Wtower
Wtower

Reputation: 19912

You can add any custom settings that you wish in your project's settings file:

MY_CUSTOM_SETTING = ...

Your custom setting can also be a dictionary if you wish not to have too many new settings.

Then you can access this setting as:

from django.conf import settings
settings.MY_CUSTOM_SETTING ...

Upvotes: 0

Related Questions