Project specific .vimrc / How to modify the python path when working in Vim
In Vim I often find the need to add my python project to the PYTHONPATH so I can run external tools, code completion etc.
Try opening a Django project in Vim and importing a model:
:cd ~/Your/Project/Dir
:!python
>>> from yoursite.yourapp import models
You’ll get the following error:
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
Which makes sense, your project source isn’t on the python path. Here’s my solution to applying project specific vim settings / updating the python path:
Add the following line to your vimrc:
" Read .vimproj in the working directory
map <silent> <leader>P :source ./.vimproj<CR>
Then create a file in your project root called .vimproj with the follwing contents:
" Mysite Specific Vimrc
let $django_dir = getcwd()."/<your django folder name>"
let $lib_dir = getcwd()."/libs"
let $site_packages_dir = "/Library/Python/2.6/site-packages/"
if !exists("g:python_dirs_loaded")
let g:python_dirs_loaded = 1
let $PYTHONPATH = $django_dir.":".$lib_dir.":".$site_packages_dir
set path=$django_dir
set path+=$lib_dir
set path+=$site_packages_dir
endif
let $DJANGO_SETTINGS_MODULE = "settings"
echo "Mysite settings loaded"
When I open a project bookmark in NerdTree, I type cd to change the working directory to the project root, then hit ,P to load the project specific settings.