I am learning Django using the book "Lightweight Django". I'm using Django 1.8. However, I can not run this code. Here is the error message:
The working tree:
build.py
import os
import shutil
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from django.test.client import Client
def get_pages():
for name in os.listdir(settings.SITE_PAGES_DIRECTORY):
if name.endswith('.html'):
yield name[:-5]
class Command(BaseCommand):
help = 'Build static site output.'
leave_locale_alone = True
def handle(self, *args, **options):
if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
os.makedirs(settings.STATIC_ROOT, exists_ok=True)
call_command('collectstatic', interactive=False, clear=True,verbosity=0)
client = Client()
for page in get_pages():
url = reverse('page', kwargs={'slug': page})
response = client.get(url)
if page == 'index':
output_dir = settings.SITE_OUTPUT_DIRECTORY
else:
output_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)
os.makedirs(output_dir)
with open(os.path.join(output_dir, 'index.html'), 'wb') as f:
f.write(response.content)
prototypes.py
import os
import sys
from django.conf import settings
BASE_DIR = os.path.dirname(__file__)
settings.configure(
DEBUG = True,
SECRET_KEY= 'qfzf!b1z^5dyk%syiokeg4*2xf%kj68g=o&e8qvd@@(1lj5z8)',
ROOT_URLCONF='sitebuilder.urls',
MIDDLEWARE_CLASSES=(),
INSTALLED_APPS=(
'django.contrib.staticfiles',
'sitebuilder',
),
TEMPLATES=(
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':[],
'APP_DIRS':True,
},
),
STATIC_URL='/static/',
SITE_PAGES_DIRECTORY=os.path.join(BASE_DIR,'pages'),
SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR,'_build'),
STATIC_ROOT=os.path.join(BASE_DIR,'_build','static'),
)
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
You have a typo, it is exist_ok
, not exists_ok
The correct code should be:
os.makedirs(settings.STATIC_ROOT, exist_ok=True)
However, that won't work for you either, because exist_ok
was added in Python 3.2. You are using Python 2.7, but the book is written for Python 3 (probably 3.4, I'm not certain)
In Python 2.7, you can catch the exception when the directory already exists:
try:
os.makedirs(settings.STATIC_ROOT)
except OSError as e:
if e.errno != errno.EEXIST:
raise
However, I strongly recommend that you switch to Python 3. You'll come across other problems if you try to write Python 3 code in Python 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With