Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i properly change the assigned secret key in a Django Web Application

So, I'm trying to deploy a Django Web App to production, but I want to change the secret key before doing so.

I've attempted to generate a new key using a randomizing function and insert that new key in place of the old one. When I do so, I get an error that says the following:

AttributeError 'module' object has no attribute 'JSONEncoder' ... Exception Location .../django/contrib/messages/storage/cookie.py in , line 9

I've deleted the browser cache and restarted the server, but the error persists. I've also attempted to change the key back, after deleting the browser cache and restarting, the error still persists.

Any idea how to resolve this issue?

Edit: Python version is 2.6.6 and Django version is 1.3.1

like image 227
Enrique Kinsey Avatar asked Mar 10 '17 19:03

Enrique Kinsey


2 Answers

So, to answer my own question, changing the assigned key is done the same way you'd change any other variable. Just create a 50 character (ideally random) string and set SECRET_KEY equal to it.

SECRET_KEY = "#$%&N(ASFGAD^*(%326n26835625BEWSRTSER&^@T#%$Bwertb"

Then restart the web application.

My problem was completely unrelated. It occurred because I set the path python uses to locate packages to a weird location. Sorry about that guys.

like image 198
Enrique Kinsey Avatar answered Oct 14 '22 03:10

Enrique Kinsey


I like to use this pattern (where you would put your app's name instead of APP_NAME):

# SECURITY WARNING: keep the secret key used in production secret!
secret_key_env_variable_name = 'APP_NAME_SECRET_KEY'
SECRET_KEY = os.environ.get(secret_key_env_variable_name)
if len(SECRET_KEY) < 25:
    print( 'The value of $%s does not contain enough characters (%s characters)' % (secret_key_env_variable_name, len(SECRET_KEY)))
    raise RuntimeError('SECRET_KEY is not long enough (in environment variable "%s"' % secret_key_env_variable_name)

Then in the account that runs Django I export this variable in the .bashrc (use your applicable environment config file):

export APP_NAME_SECRET_KEY='oysmy1iv=n7ygq%og!b4@(k@40&5d-i&5%^c8$riw%3$r3yi(='

Note: that key was randomly generated with the first url for a generator after web searching for: generate a secret_key django.

like image 32
sage Avatar answered Oct 14 '22 04:10

sage