- Web Development with Django Cookbook(Second Edition)
- Aidas Bendoraitis
- 220字
- 2021-07-23 14:31:58
Defining relative paths in the settings
Django requires you to define different file paths in the settings, such as the root of your media, the root of your static files, the path to templates, the path to translation files, and so on. For each developer of your project, the paths may differ as the virtual environment can be set up anywhere and the user might be working on Mac OS X, Linux, or Windows. Anyway, there is a way to define these paths that are relative to your Django project directory.
Getting ready
To start with, open settings.py
.
How to do it…
Modify your path-related settings accordingly instead of hardcoding the paths to your local directories, as follows:
# settings.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals import os BASE_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), "..") ) MEDIA_ROOT = os.path.join(BASE_DIR, "myproject", "media") STATIC_ROOT = os.path.join(BASE_DIR, "myproject", "static") STATICFILES_DIRS = ( os.path.join(BASE_DIR, "myproject", "site_static"), ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, "myproject", "templates"), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) FILE_UPLOAD_TEMP_DIR = os.path.join( BASE_DIR, "myproject", "tmp" )
How it works…
At first, we define BASE_DIR
, which is an absolute path to one level higher than the settings.py
file. Then, we set all the paths relative to BASE_DIR
using the os.path.join
function.
See also
- The Including external dependencies in your project recipe
- Facebook Application Development with Graph API Cookbook
- Node.js Design Patterns
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- PowerCLI Cookbook
- AngularJS深度剖析與最佳實(shí)踐
- Learning Network Forensics
- Mastering Predictive Analytics with Python
- Access 2010數(shù)據(jù)庫應(yīng)用技術(shù)實(shí)驗(yàn)指導(dǎo)與習(xí)題選解(第2版)
- Machine Learning With Go
- JavaScript機(jī)器人編程指南
- Microsoft Exchange Server 2016 PowerShell Cookbook(Fourth Edition)
- Applied Deep Learning with Python
- Python Automation Cookbook
- C Primer Plus(第6版)中文版【最新修訂版】
- Python程序設(shè)計(jì)案例教程