Organising your Django code
There are several options when it comes to organising your code in a Django project. There isn’t a ‘correct’ way, and it will depend on the size of the project, if it is a team development, or purely the preference of the developer.
Django gives you the ability to put your templates anywhere, either in single or multiple locations. You can add a path to your TEMPLATE_DIRS setting, and Django will look at each path in turn to try and find your template to render.
Have a single template directory, which contains all the templates for all your project apps. The benefit here is that everything is in one place. If your project is split up into a lot of apps, and there is crossover between apps, you may struggle to find where you put a template further down the line.
Another advantage is if you have a dedicated content team who just work on templates, and you either don’t want to bother them with python code, or you just don’t want them to go near it, you can keep it separate. I’ve used this method, and the templates were kept in a separate source repository to the code.
The disadvantage is that if you don’t have a good system for arranging the directories within your templates directory, you’ll still struggle to find things. So have a good strategy for file naming conventions if you go this route.
Have a template directory in each of your installed apps. If your apps are self contained, this is a good option, as it will be easy to organise. Email templates in your email app, user profile templates in your user profile app.
The only problems you get here is when you have an app whose functionality spans more than one app, or more than one app accesses the same template. You then have to decided where best to put it.
Media really has to be in a single location so that it can be served by whichever webserver you choose. But you still have the option of having the media stored somewhere within the project, or external to the project. Again, when working within a team that has graphic designers, it can be beneficial to keep media outside the project. It also makes sense if you want to re-use the media in another project.
Your template tags need to be inside a directory named templatetags, which has to reside inside an app. If you have multiple apps, with multiple template tag directories, it can be an issue finding the correct app where the template tag lives.
If you want to put all your template tags in one place, and use them across your project, you can create an app specifically for your template tags. Create your app, place a templatetags directory in it, with an __init__.py file, and remember to add the app to the INSTALLED_APPS setting.
Do you have any tips when it comes to organising your code? Anything here you agree or don’t agree with? Have your say and leave a comment below.