Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
268 views

Organization - Best Practice For Django Project Working Directory Structure - Stack Overflow

The document discusses best practices for organizing Django project directories on a development machine. It recommends the following directory structure: 1. A top-level "projects" directory containing all development projects. 2. Within each project directory: directories for the project code, virtual environment, static/media files, documentation, database, and other common files. 3. The project code directory contains subdirectories for apps, settings, templates, and other code-related files. 4. Settings files are organized into different environment-specific files (production, development, etc). 5. Requirements are specified in setup.py rather than a separate requirements.txt file. 6. A "tmp" directory
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
268 views

Organization - Best Practice For Django Project Working Directory Structure - Stack Overflow

The document discusses best practices for organizing Django project directories on a development machine. It recommends the following directory structure: 1. A top-level "projects" directory containing all development projects. 2. Within each project directory: directories for the project code, virtual environment, static/media files, documentation, database, and other common files. 3. The project code directory contains subdirectories for apps, settings, templates, and other code-related files. 4. Settings files are organized into different environment-specific files (production, development, etc). 5. Requirements are specified in setup.py rather than a separate requirements.txt file. 6. A "tmp" directory
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

9/4/2016 organizationBestpracticefordjangoprojectworkingdirectorystructureStackOverflow

signup login tour help

Dismiss

AnnouncingStackOverflowDocumentation
WestartedwithQ&A.Technicaldocumentationisnext,andweneedyourhelp.

Whetheryou'reabeginneroranexperienceddeveloper,youcancontribute.

Signupandstarthelping LearnmoreaboutDocumentation

Bestpracticefordjangoprojectworkingdirectorystructure

Iknowthereisactuallynosinglerightway.HoweverI'vefoundthatit'shardtocreateadirectorystructurethatworkswellandremaincleanfor
everydeveloperandadministrator.Thereissomestandardstructureinmostprojectsongithub.Butitdoesnotshowawaytoorganizeanother
filesandallprojectsonpc.

Whatisthemostconvenientwaytoorganizeallthesedirectoriesondevelopmentmachine?Howdoyounamethem,andhowdoyouconnect
anddeploythistoserver?

projects(allprojectsthatyourareworkingon)
sourcefiles(theapplicationitself)
workingcopyofrepository(Iusegit)
virtualenvironment(Iprefertoplacethisneartheproject)
staticroot(forcompiledstaticfiles)
mediaroot(foruploadedmediafiles)
README
LICENSE
documents
sketches
examples(anexampleprojectthatusestheapplicationprovidedbythisproject)
database(incasesqliteisused)
anythingelsethatyouusuallyneedforsuccessfulworkonproject

TheproblemsthatIwanttosolve:

Goodnamesofdirectoriessothattheirpurposeisclear.
Keepingallprojectfiles(includingvirtualenv)inoneplace,soIcaneasilycopy,move,archive,removewholeprojectorestimatediskspace
usage.
Creatingmultiplecopiesofsomeselectedfilesetssuchasentireapplication,repositoryorvirtualenv,whilekeepingsinglecopyofanother
filesthatIdon'twanttoclone.
Deployingrightsetoffilestotheserversimplybyrsyncingselectedonedir.

django organization

editedMay1'14at14:31 askedApr3'14at15:09
raacer
944 1 10 24

4Answers

There'retwokindofDjango"projects"thatIhaveinmy ~/projects/ directory,bothhaveabit


differentstructure.:

Standalonewebsites
Pluggableapplications

Standalonewebsite
Mostlyprivateprojects,butdoesn'thavetobe.Itusuallylookslikethis:

~/projects/project_name/

http://stackoverflow.com/questions/22841764/bestpracticefordjangoprojectworkingdirectorystructure 1/6
9/4/2016 organizationBestpracticefordjangoprojectworkingdirectorystructureStackOverflow
docs/#documentation
scripts/
manage.py#installedtoPATHviasetup.py
project_name/#projectdir(theonewhichdjangoadmin.pycreates)
apps/#projectspecificapplications
accounts/#mostfrequentapp,withcustomusermodel
__init__.py
...
settings/#settingsfordifferentenvironments,seebelow
__init__.py
production.py
development.py
...

__init__.py#containsprojectversion
urls.py
wsgi.py
static/#sitespecificstaticfiles
templates/#sitespecifictemplates
tests/#sitespecifictests(mostlyinbrowserones)
tmp/#excludedfromgit
setup.py
requirements.txt
requirements_dev.txt
pytest.ini
...

Settings

Themainsettingsareproductionones.Otherfiles(eg. staging.py , development.py )simply


importeverythingfrom production.py andoverrideonlynecessaryvariables.

Foreachenvironment,thereareseparatesettingsfiles,eg.production,development.Isome
projectsIhavealsotesting(fortestrunner),staging(asacheckbeforefinaldeploy)andheroku
(fordeployingtoheroku)settings.

Requirements

Iratherspecifyrequirementsinsetup.pydirectly.Onlythoserequiredfordevelopment/test
environmentIhavein requirements_dev.txt .

Someservices(eg.heroku)requirestohave requirements.txt inrootdirectory.

setup.py

Usefulwhendeployingprojectusing setuptools .Itadds manage.py to PATH ,soIcanrun


manage.py directly(anywhere).

Projectspecificapps

Iusedtoputtheseappsinto project_name/apps/ directoryandimportthemusingrelative


imports.

Templates/static/locale/testsfiles

Iputthesetemplatesandstaticfilesintoglobaltemplates/staticdirectory,notinsideeachapp.
Thesefilesareusuallyeditedbypeople,whodoesn'tcareaboutprojectcodestructureorpython
atall.Ifyouarefullstackdeveloperworkingaloneorinasmallteam,youcancreateperapp
templates/staticdirectory.It'sreallyjustamatteroftaste.

Thesameappliesforlocale,althoughsometimesit'sconvenienttocreateseparatelocale
directory.

Testsareusuallybettertoplaceinsideeachapp,butusuallythereismanyintegration/functional
testswhichtestsmoreappsworkingtogether,soglobaltestsdirectorydoesmakesense.

Tmpdirectory

Thereistemporarydirectoryinprojectroot,excludedfromVCS.It'susedtostoremedia/static
filesandsqlitedatabaseduringdevelopment.Everythingintmpcouldbedeletedanytimewithout
anyproblems.

Virtualenv

Iprefer virtualenvwrapper andplaceallvenvsinto ~/.venvs directory,butyoucouldplaceit


inside tmp/ tokeepittogether.

Projecttemplate

I'vecreatedprojecttemplateforthissetup,djangostarttemplate

Deployment

Deploymentofthisprojectisfollowing:

source$VENV/bin/activate
exportDJANGO_SETTINGS_MODULE=project_name.settings.production
gitpull
pipinstallrrequirements.txt

#Updatedatabase,staticfiles,locales

http://stackoverflow.com/questions/22841764/bestpracticefordjangoprojectworkingdirectorystructure 2/6
9/4/2016 organizationBestpracticefordjangoprojectworkingdirectorystructureStackOverflow
manage.pysyncdbnoinput
manage.pymigrate
manage.pycollectstaticnoinput
manage.pymakemessagesa
manage.pycompilemessages

#restartwsgi
touchproject_name/wsgi.py

Youcanuse rsync insteadof git ,butstillyouneedtorunbatchofcommandstoupdateyour


environment.

Recently,Imade [djangodeploy][2] app,whichallowsmetorunsinglemanagementcommand


toupdateenvironment,butI'veuseditforoneprojectonlyandI'mstillexperimentingwithit.

Sketchesanddrafts

DraftoftemplatesIplaceinsideglobal templates/ directory.Iguessonecancreatefolder


sketches/ inprojectroot,buthaven'tusedityet.

Pluggableapplication

Theseappsareusuallypreparedtopublishasopensource.I'vetakenexamplebelowfrom
djangoforme

~/projects/djangoapp/

docs/
app/
tests/
example_project/
LICENCE
MANIFEST.in
README.md
setup.py
pytest.ini
tox.ini
.travis.yml
...

Nameofdirectoriesisclear(Ihope).Iputtestfilesoutsideappdirectory,butitreallydoesn't
matter.Itisimportanttoprovide README and setup.py ,sopackageiseasilyinstalledthrough
pip .

editedMay13'15at16:16 answeredMay5'14at9:40
perror elvard
3,130 7 27 51 1,364 1 7 11

Thankyou!Ilikeyourstructure.Itgavemeusefullideas.Goodpointsaboutusingsetup.pyforrequirements
andinstallingmanage.pyintoPATH.Couldyoupleaseshowhowyoudothelastthing?Alsogoodpoint
about'tmp'dir.I'drathernameit'local',thenImayhave'env','tmp'andanythingalsoinside.Thissolvesthe
problemofhavingtoomanydealswithgitignore.Anewproblemisthatthisnameistoocloseto'locale'.
Maybeitmakessensetomove'locale'tocoreapp'project_name',notsure.Justdontwanttochange
structurebecauseofbadname.Anysuggestions? raacer May5'14at17:05

Whenusingsetup.py,add scripts keywordargument: github.com/elvard/djangostart


template/blob/master/project/
Ilike tmp becauseitsuggests"somethingtemporary"whichcanbe

removedanytime.Toplevel locale dirisn'tnecessary,youcanplaceitanywhere.Ijustlikeittobe
consistentwithstatic/templatesdirs.elvardMay5'14at17:11

Myrequirementforabilitytomakeseveralcopiesofsourcefileswithoutcopyinganotherfilesisnotsolved
directly.Butthegoalstillmaybearchivedbyusing gitcheckout orbyexcludingjustonedir'tmp'when
cloningtheprojectdirectory.Soitseemsyourstructuremeetsallrequirements,anditisclearenoughto
useonregularbasiswithoutanydoubt.I'macceptingyouranswer.Thankyou. raacer May6'14at19:15

Thankyou.Istilldon'tunderstandwhatyoumeanby"abilitytomakeseveralcopiesofsourcefileswithout
copyinganotherfiles".Tweakedrsynccommandwoulddo,butthatisn'tprobablywhatyoumean...elvard
May7'14at20:36

Iusuallycreatedir src insideofprojectroot.Thisistheworkingcopyofsourcefilesandthegitrepository


root.Icanmakeseveralcopiesofthisdirectory src , src.bak , src_tmp andsoon.Othernonrepodirs
like env , tmp , media , backup resideonthesamelevel.SoIcanjust cprsrcsrc.bak anytimeI
wanttodosomeexperimentwithgitortocompareversionswithexternaltool.Whileyouhavelocalfiles
insideofyourrepository,Ihaverepositoryinsideofmylocalfilesdir(viceversa).Thebetternameofmy
src diris repo . raacer May8'14at1:33

Myanswerisinspiredonmyownworkingexperience,andmostlyinthebookTwoScoopsof
DjangowhichIhighlyrecommend,andwhereyoucanfindamoredetailedexplanationof
everything.Ijustwillanswersomeofthepoints,andanyimprovementorcorrectionwillbe
welcomed.Buttherealsocanbemorecorrectmanerstoachievethesamepurpose.

Projects
IhaveamainfolderinmypersonaldirectorywhereImantainalltheproyectswhereIamworking

http://stackoverflow.com/questions/22841764/bestpracticefordjangoprojectworkingdirectorystructure 3/6
9/4/2016 organizationBestpracticefordjangoprojectworkingdirectorystructureStackOverflow
on.

SourceFiles
Ipersonallyusethedjangoprojectrootasrepositoryrootofmyprojects.Butinthebookis
recommendedtoseparateboththings.Ithinkthatthisisabetterapproach,soIhopetostart
makingthechangeprogressivelyonmyprojects.

project_repository_folder/
.gitignore
Makefile
LICENSE.rst
docs/
README.rst
requirements.txt
project_folder/
manage.py
media/
app1/
app2/
...
appn/
static/
templates/
project/
__init__.py
settings/
__init__.py
base.py
dev.py
local.py
test.py
production.py
ulrs.py
wsgi.py

Repository
GitorMercurialseemtobethemostpopularversioncontrolsystemsamongDjangodevelopers.
AndthemostpopularhostingservicesforbackupsGitHubandBitbucket.

VirtualEnvironment
Iusevirtualenvandvirtualenvwrapper.Afterinstallingthesecondone,youneedtosetupyour
workingdirectory.Mineisonmy/home/envs directory,asitisrecommendedon
virtualenvwrapperinstallationguide.ButIdon'tthinkthemostimportantthingiswhereisitplaced.
Themostimportantthingwhenworkingwithvirtualenvironmentsiskeepingrequirements.txtfile
uptodate.

pipfreezel>requirements.txt

StaticRoot
Projectfolder

MediaRoot
Projectfolder

README
Repositoryroot

LICENSE
Repositoryroot

Documents
Repositoryroot.Thispythonpackagescanhelpyoumakingeasiermantainingyour
documentation:

reStructuredText
Sphinx

Sketches

Examples

Database

answeredMay1'14at10:01
cor
1,892 9 31

Thankyouforsharingyourexperience.Thereisalotof'project*'directoriesinyourstructure.Youprobably
don'tusesuchnamesinreallife,right?Let'ssaywehavea'todo'project.Howdoyounamethesedirsin
suchcase?TheproblemthatIseeinyourcurrentstructureismixingrepositorywithnonrepositoryfiles(as
younotedabove).Itmaybeannoyingtoaddanytrashto.gitignore,isnotit?Anotherdubiousthingis
keepingtheenvdirsofarfromtheprojectitself.Doesitmakesense?Whynottocreate~/docs,~/statics
andsoon?Evengitlikestositnearthesourcefiles. raacer May1'14at13:48

Iwouldnamethem:"todo_project">todo>todo(ormaybetodoapp).Ithinkthatisimportantbeeingthe
repositoryfolderintherootofthedirecectoryhierarchy.But,isjustmyopinion.Abouttheenvironment
directory,whenyouneedtosetuptheproductionenvironment,youaredonewithjusttypeing:pipinstallU
rrequirements.txt.But,asIsaid,thereisnotonesolutionforeverything.corMay1'14at15:18

Sothepathtomainappis"projects/todo_project/todo/todo".Word"projects"repeatedtwice,andword
"todo"repeatedthreetimes.Thisseemslike"projects/project/my_project/project_dir/project/project".The
namesareveryunclear.ThisisoneofmajorproblemsthatI'mtryingtosolveinmydirectorystructure.I

http://stackoverflow.com/questions/22841764/bestpracticefordjangoprojectworkingdirectorystructure 4/6
9/4/2016 organizationBestpracticefordjangoprojectworkingdirectorystructureStackOverflow
wanttonamethedirectoriestomakeiteasytounderstandthehierarchy.Whataboutrepositoryroot,could
youpleaseexplainwhyit'simportant?Alsocouldyoupleaseexplainwhatisgoodaboutkeepingenvs
outsideofmainprojectdir? raacer May2'14at14:48

Idon'tliketocreateanew settings/ directory.Isimplyaddfilesnamed settings_local.py and


settings_remote.py soIdon'thavetoeditthe BASE_DIR .Theapproachbelowincreasethe
defaultstructureinsteadofchangingit.

mysite/#Project
conf/
locale/
en_US/
fr_FR/
it_IT/
mysite/
__init__.py
settings.py#Forsomeonebase.py
settings_local.py#Forsomeonelocal.py
settings_remote.py#Forsomeoneproduction.py
urls.py
wsgi.py
static/
admin/
css/#Custombackendstyles
css/#Projectfrontendstyles
fonts/
images/
js/
sass/
staticfiles/
templates/#Projecttemplates
includes/
footer.html
header.html
index.html
myapp/#Application
core/
migrations/
__init__.py
templates/#Applicationtemplates
myapp/
index.html
static/
myapp/
js/
css/
images/
__init__.py
admin.py
apps.py
forms.py
models.py
models_foo.py
models_bar.py
views.py
templatetags/#Applicationwithcustomcontextprocessorsandtemplatetags
__init__.py
context_processors.py
templatetags/
__init__.py
templatetag_extras.py
gulpfile.js
manage.py
requirements.txt

Ithinkthis:

settings.py
settings_local.py
settings_remote.py

isbetterthanthis:

settings.py
local_settings.py
remote_settings.py

Thisconceptappliestootherfilesaswell.

Iusuallyplace node_modules/ and bower_components/ intheprojectdirectorywithinthedefault


static/ folder.

Sometimea vendor/ directoryforGitSubmodulesbutusuallyIplacetheminthe static/ folder.

editedFeb8at19:46 answeredFeb6at17:49
isar
149 9

HereiswhatIfollowonMysystem.

1. AllProjects:Thereisaprojectsdirectoryinmyhomefolderi.e. ~/projects .Allthe

http://stackoverflow.com/questions/22841764/bestpracticefordjangoprojectworkingdirectorystructure 5/6
9/4/2016 organizationBestpracticefordjangoprojectworkingdirectorystructureStackOverflow
projectsrestinsideit.
2. IndividualProject:Ifollowastandardizedstructuretemplateusedbymanydevelopers
calleddjangoskelforindividualprojects.Itbasicallytakescareofallyourstaticfileand
mediafilesandall.
3. Virtualenvironment:Ihaveavirtualenvsfolderinsidemyhometostoreallvirtual
environmentsinthesystemi.e. ~/virtualenvs .ThisgivesmeflexibilitythatIknowwhatall
virtualenvironmentsIhaveandcanlookuseeasily

Theabove3arethemainpartitionsofMyworkingenvironment.

Alltheotherpartsyoumentionedaremostlydependentonprojecttoprojectbasis(i.e.you
mightusedifferentdatabasesfordifferentprojects).Sotheyshouldresideintheirindividual
projects.

answeredMay1'14at10:32
Sahilkalra
2,360 1 9 16

Thankyou.Itmaybeannoyingtoaddanytrashto.gitignorewhenmixingrepositorywithnonrepository
files.Isnotit?Someofmyprojectshaveuptotenandmoresuchfilesanddirs,sothismakesrealproblem
forme.Anotherdubiousthingiskeepingtheenvdirsofarfromtheprojectitself.Whatistheflexibilityin
suchsolution?Whynottocreate~/docs,~/staticsandsoon?Evengitlikestositnearthesourcefiles.I
thoughtflexibilityiswhenIcanjustcopy/move/archive/removewholeprojectdirectoryincludingvirtualenv
andcanmaintainmultipleenvswithinoneprojecteasily raacer May1'14at14:04

http://stackoverflow.com/questions/22841764/bestpracticefordjangoprojectworkingdirectorystructure 6/6

You might also like