This post will show you how to create a local_contants.py file using Django South. If you're not familiar with South, it's a data migration tool. Stated differently, it's a tool that helps keep your database changes current across different sandboxes and server environments.
The reason you may want to have constants is when you have a type model instance that you want to reference in your code for decision logic. For example, you might display things differently if your contact method type ID is 1 (email) vs 2 (phone). Typically, you keep these in constants.py file. Although sometimes you can put this data in a fixture, for various reasons sometimes fixtures is not the ideal solution.
The code below is designed to be run inside a migration to update your local_constants.py file with data that you just migrated. local_constants.py is a locally maintained file. This means, that like your local_settings.py, it should not be in the repo. For example:
set_constant('/home/projects/sample/local_constants.py','STAMP_MW_ID',42,'Set from sample.0007_add_constants.py')
The constant searching could be improved, feel free to post enhancements!
defset_constant(file,constant,value,comment=''):''' Search through file for the constant and either adds it to the end or updates the existing value. Comment is optionally passed and is placed on the same line as the constant along with the modification date/time. Comment is only updated if the value is updated. It's recommended that the file for local_constants.py be different than the file checked into your repo as it's locally maintained. Example: set_constant('a.txt', 'TYPE', 1, 'This is optional') Author: Ed Menendez ([email protected]) '''write_file=found_constant=Falseifcomment:comment+=' 'line_to_write='%s = %s # %sLast modified %s\n'% \
(constant,value.__repr__(),comment,datetime.datetime.now())# The file to be written is stored here.new_file=''try:f=open(file,'r+')exceptIOError:# Nothing to search through here. Move along.f=Noneelse:# Loop through the file and look for the stringforlineinf.readlines():ifline.find(constant)>-1:line_splits=line.split('=')iflen(line_splits)==2:# Yes, it's an assignment line.old_constant,old_value=line_splitsold_constant=old_constant.strip()ifold_constant==constant:# We've found the contant!found_constant=Trueold_value_splits=old_value.split('#')iflen(old_value_splits)==2:old_value,trash=old_value_splitselse:old_value=old_value_splits[0]old_value=old_value.strip()ifold_value!=value.__repr__():# It's changed!write_file=Trueline=line_to_writenew_file+=linef.close()# If nothing found, then add it to the endifnotfound_constant:write_file=True# New line needs to be added in case the file doesn't end with a new# line. Could be made smarter and check for the newline. This will make# for a prettier local_constants.pynew_file+='\n'+line_to_writeifwrite_file:# Write out the new filef=open(file,'w+')f.write(new_file)f.close()