[Django]-Django โ€“ setting up urls.py and views.py

2๐Ÿ‘

โœ…

Have you defined the template path in TEMPLATE_DIRS.

settings.py

# at start add this
import os, sys

abspath = lambda *p: os.path.abspath(os.path.join(*p))

PROJECT_ROOT = abspath(os.path.dirname(__file__))
sys.path.insert(0, PROJECT_ROOT)

TEMPLATE_DIRS = (
    abspath(PROJECT_ROOT, 'templates'), # this will point to mysite/mysite/templates
)

Then move your templates folder to mysite > mysite > templates

Then instead of return render(request, "templates/index.html") just do like this return render(request, "index.html"). This should work.

Your directory structure should be:

mysite/
      mysite/
          __init__.py
          settings.py
          urls.py
          wsgi.py

          templates/
              index.html
          static/
              css/
              js/
          app/
               __init__.py
               admin.py
               models.py
               tests.py
               urls.py
               views.py
๐Ÿ‘คAamir Rind

3๐Ÿ‘

On top of setting up your TEMPLATE_DIRS in settings.py:

import os

ROOT_PATH = os.path.dirname(__file__)

TEMPLATE_DIRS = (    
    os.path.join(ROOT_PATH, 'templates'),
)

mysite/urls.py

urlpatterns = patterns('',
    url(r'^$', include('app.urls', namespace='app'), name='app'),
)

app/urls.py

urlpatterns = patterns('app.views',
    url(r'^$', 'index', name='index'),
)

In your views.py code as is, change templates/index.html to index.html and the template should go under:

mysite/mysite/templates/index.html

On another note, your css, js and img folders are best placed somewhere else like a mysite/static folder.

๐Ÿ‘คThierry Lam

Leave a comment