I am a beginner at django and python and i am currently stuck at Creating our home page of the Django tutorial. I am getting a "TemplateDoesNotExist at error" error. I am also using windows. What am I doing wrong?
Settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup#1$8obt2_+&k3q+pmu)5%asj6yjpkag')
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catalog.apps.CatalogConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'locallibrary.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'locallibrary.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
StackTrace:
TemplateDoesNotExist at /catalog/
index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/
Django Version: 2.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: C:\Users\AjitGoel\Envs\my_django_environment\Scripts\python.exe
Python Version: 3.7.2
Python Path:
['C:\\Users\\AjitGoel\\django-projects\\locallibrary',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\Scripts\\python37.zip',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\DLLs',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\lib',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\Scripts',
'c:\\users\\ajitgoel\\appdata\\local\\programs\\python\\python37\\Lib',
'c:\\users\\ajitgoel\\appdata\\local\\programs\\python\\python37\\DLLs',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\lib\\site-packages']
Server time: Sun, 10 Feb 2019 23:21:43 -0600
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: C:\Users\AjitGoel\django-projects\locallibrary\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
base_generic.html:
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>Local Library</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Add additional CSS in static file -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<li>Home</li>
<li>All books</li>
<li>All authors</li>
</ul>
{% endblock %}
</div>
<div class="col-sm-10 ">{% block content %}{% endblock %}</div>
</div>
</div>
</body>
</html>
Views.py:
from django.shortcuts import render
from catalog.models import Book, Author, BookInstance, Genre
def index(request):
# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact='a').count()
# The 'all()' is implied by default.
num_authors = Author.objects.count()
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context=context)
index.html:
{% extends "base_generic.html" %}
{% block content %}
<h1>Local Library Home</h1>
<p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
<h2>Dynamic content</h2>
<p>The library has the following record counts:</p>
<ul>
<li><strong>Books:</strong> {{ num_books }}</li>
<li><strong>Copies:</strong> {{ num_instances }}</li>
<li><strong>Copies available:</strong> {{ num_instances_available }}</li>
<li><strong>Authors:</strong> {{ num_authors }}</li>
</ul>
{% endblock %}
If you want to place the template in-app level follow the directory structure like this
templates/<app_name>/your_template
Then in view.py use like this
return render(request, '<app_name>/your_template', context=context)
If you want to place the template in root templates directory follow the structure like this
templates/<app_name>/your_template
Then in view.py use like this
return render(request, '<app_name>/your_template', context=context)
os.path.join(BASE_DIR, 'templates')
By this line of code you are adding that templates should be in your root folder of your project. Create templates folder in your root directory of your project.
templates directory in your project you should add in settings.py in TEMPLATES_DIRS like this
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "/localllibrary/templates"),
)
what it does is it will look for your created template i.e. index.html in directory specified here. If you see it is a tuple or can be a list so you add multiple directories here. BASE_DIR is the root of you django project that is relative not hardcoded.
You file Structure should be like this:
myProject
├── myProject
| ├── __init__.py
| ├── settings.py
| ├── urls.py
| ├── wsgi.py
├── myApp
| ├── static <-- Static files can go here
| | ├── myApp <-- Create a folder with the same name as the app name, recommended but not required
| | | ├── css
| | | | ├── style.css
| | | ├── js
| | | | ├── some.js
| ├── templates <-- Templates can be here
| | ├── myApp <-- Create a folder with the same name as the app name, recommended but not required
| | | ├── index.html
| | | ├── other.html
| ├── __init__.py
| ├── models.py
| ├── urls.py
| ├── views.py
├── templates <-- Templates can be here too
| ├── sometemplate.html
├── static <-- Static files can go here too
| ├── css
| | ├── somecss.css
| ├── js
Now if your templates/static files is inside the templates/static folder at your project root, you can refer to them easily as someplace.html or css/somecss.css.
While if it's inside the template folder in your app like this:
myApp --> templates --> myTemplate.html
Then you can use it like this: myTemplate.html. But it's recommended to create another folder inside the templates folder with app name to avoid confusion, like this:
myApp --> templates --> myApp --> myTemplate.html
Now you will refer to it like this: myApp/myTemplate.html, it avoids confusion as you will know from which app template is coming from, also it makes it possible to have templates with same name(say index.html or base.html) in multiple apps. Same goes for static files.
Related
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs.
Setting.py
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'technicalCourse.apps.TechnicalcourseConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\template'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'website.wsgi.application'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
r'website\technicalCourse\static',
]
This the template file
<!DOCTYPE html>
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/simple.css' %}">
</head>
<body>
<img src="{% static 'image/img.png' %}">
<h1>Welcome to course on programming</h1>
<ol>
{% for x in ac %}
<li>{{x.courseName}}</li>
{% endfor %}
</ol>
</body>
For testing I simply change the color of the h1 tag alone. The css file.
h1{
color:black;
}
Structure
C:.
├───migrations
│ └───__pycache__
├───static
│ ├───css
│ └───image
├───template
│ └───technicalCourse
└───__pycache__
But there is no reflection on the webpage.
Hoping for the solution.
Thanks in advance.
try this command:
python manage.py collectstatic
and check again.
It's weird that images are working and CSS isn't. There could be a multitude of possibilities for your problem.
The simplest way to solve this is to set the path to the CSS files via an absolute or a relative path.
Relavtive path case
<link href="/static/ui/css/base.css" rel="stylesheet">
I was suffering with same problem but solved by adding the
{% load static %}
{
<link rel="stylesheet" type="text/css" href="{% static 'thumbnail_searcher/style.css' %}">
}
in same tag. For example in your case add load and link into <head> tag.
clear browser cache
in settings.py change STATIC_URL = "static/" to STATIC_URL = "/static/"
run python manage.py runserver port_number(optional)
Try
$ python manage.py findstatic css/style.css
instead of css/style.css add your own path
If Django project able to locate the CSS, it will return path to your CSS file.
Then restart your project and it should work.
I'm just learning Django and Python and want to be sure I'm doing things the right DRY way and I'm sure there's a MUCH easier way to do this...
Right now, I have the following base_template_tags.py as it's own app (added into settings.py and loaded on the HTML template {% load ... %} that allows me to access the year as an HTML tag via {% cd_year %} and/or the email address as { cd_email }. It works... but it's a hack.
Is there a better way?
from datetime import datetime
from django import template
register = template.Library()
#register.simple_tag
def current_time(format_string):
return datetime.datetime.now().strftime(format_string)
#register.simple_tag
def cd_year():
return datetime.now().year
#register.simple_tag
def cd_email():
return 'pp#pp.com'
As you guessed, there is a much more easier way built-in to django:
{% now "Y" %}
Edit
As you mentioned in the comments that you want to share a bunch of template tags among all of your apps, you can override libraries dictionary and add your custom template tags there.
Read more about that in the docs
and for your templates:
{% load your_template_tags_file_name %}
{% cd_year %}
Edit 2
This is how the TEMPLATES part of your settings.py should look like:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries': { # <-----------
'global_tags': 'template_tags.global_tags',
'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
},
},
},
]
and your directory structure should be like:
<your_project_dir>
├── __init__.py
├── settings.py
├── template_tags
│ ├── global_tags.py
│ ├── __init__.py
...
the global_tags.py file should contain your template tag definition and registration, as:
from datetime import datetime
from django import template
register = template.Library()
#register.simple_tag
def current_time(format_string):
return datetime.now().strftime(format_string)
#register.simple_tag
def cd_year():
return datetime.now().year
#register.simple_tag
def cd_email():
return 'pp#pp.com'
and for each template that's going to use those custom template tags:
{% load global_tags %}
{% cd_year %}
You can used below code in .html
{% block content %}
{% load staticfiles %}
{% endblock %}
Create a new folder “static” in the root of the main project.
Same level as the “templates” directory.
Add this code to your base template file (__base.html).
{% load staticfiles %}
Use this to load the files.
Add this to your settings.py file.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Create global context:
You have create App inside context_processor.py file
In context_processor file written:
from app.model import *
from django.contrib.auth.models import user
def employee_processor(request):
try:
emp_obj= Employees.object.filter(user=request.user)
return { ’employee’:emp_obj}
except:
user_obj=User.object.filter(id=request.user)
return { ’employee’: user_obj}
Add your context processor in your setting py file:
TEMPLATES = [{
# whatever comes before
'OPTIONS': {
'context_processors': [
# whatever comes before
"your_app.context_processors.employee_processor",
],
}
}]
Then you can used global variables in your HTML template
{{ employee }}
{{ employee.name }}
django/
db.sqlite3
helloworld/
__init__.py
context_processors/
__init__.py
google_anlytics.py
settings.py
urls.py
wsgi.py
manage.py
polls/
__init__.py
admin.py
migrations/
models.py
templates/
polls/
home.html
tests.py
urls.py
views.py
templates/
ga.html
I am following this article to add google analytics to my django http://www.nomadblue.com/blog/django/google-analytics-tracking-code-into-django-project/
ive added GOOGLE_ANALYTICS_PROPERTY_ID and GOOGLE_ANALYTICS_DOMAIN to helloworld/settings.py
Ive added the following to
hellowworld/context_processors/google_analytics.py
from django.conf import settings
def google_analytics(request):
"""
Use the variables returned in this function to
render your Google Analytics tracking code template.
"""
ga_prop_id = getattr(settings, 'GOOGLE_ANALYTICS_PROPERTY_ID', False)
ga_domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', False)
if not settings.DEBUG and ga_prop_id and ga_domain:
return {
'GOOGLE_ANALYTICS_PROPERTY_ID': ga_prop_id,
'GOOGLE_ANALYTICS_DOMAIN': ga_domain,
}
return {}
Then, I added 'helloworld.context_processors.google_analytics.google_analytics', to helloworld/settings.py
I added ga.html in templates
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '{{ GOOGLE_ANALYTICS_PROPERTY_ID }}', '{{ GOOGLE_ANALYTICS_DOMAIN }}');
ga('send', 'pageview');
I've made sure my django project acn see the templates dir
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
I want to add the following to polls/templates/polls/home.html
{% if GOOGLE_ANALYTICS_PROPERTY_ID %}
{% include "path/to/your/ga.html" %}
{% endif %}
QUESTION:
Now on the second line it says "path/to/your/ga.html"
I am not sure what to put there.
is it ../../../templates/ga.html?
I just put
{% if GOOGLE_ANALYTICS_PROPERTY_ID %}
{% include "ga.html" %}
{% endif %}
and it found it
My 404.html page does not reference my finale.css file.
My directory structure
musicworld/
musicworld/
__pycache__
__int__.py
settings.py
urls.py
wsgi.py
feature/
__pycache__
migrations
static/
feature/
finale.css
templates/
feature/
about.html
detail.html
404.html
500.html
index.html
template.html
__init__.py
admin.py
models.py
tests
This is where in index.html I'm referencing the css
<link rel="stylesheet" type="text/css" href="{% static 'feature/finale.css' %}" />
But 404.html that extends index.htmlis not referencing the css
{% extends "index.html" %}
{% load staticfiles %}
{% block 404page %}
<div class="box">
<p class="box-message" data-dead-message="AAAAAHHHHHH!">Oh No! Something went wrong.Punish the developer by clicking here.</p>
</div>
<div class="robot">
<img src="" alt="Robot" />
</div>
{% endblock %}
static reference in settings.py
STATIC_URL = '/static/'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Both the index.htmland template.html are placed in the same folder and are properly referencing the css.Plus all the html pages in feature that are extending index.html are also referencing the css.But both 404.html and 500.htmlare not.
I've followed this tutorial to make a sample project. The structure of the files is:
- mysite
- mysite
- __init__.py
- settings.py
- urls.py
- wsgi.py
- polls
- migrations
- templates
- polls.html
- static
- script.js
- style.css
- admin.py
- models.py
- tests.py
- urls.py
- views.py
- manage.py
Everything works well, but, the problem is using of Django-pipeline for managing the assets. I've configured my project as same as below codes, but it doesn't load assets properly.
settings.py
INSTALLED_APPS = (
.
.
'django.contrib.staticfiles',
'pipeline',
'polls',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
PIPELINE_ENABLED = True
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'
PIPELINE_CSSMIN_BINARY = 'cssmin'
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.slimit.SlimItCompressor'
PIPELINE_CSS = {
'pollsX': {
'source_filenames': (
'style.css',
),
'output_filename': 'styles1.css',
'variant': 'datauri',
},
}
PIPELINE_JS = {
'pollsX': {
'source_filenames': (
'script.js',
),
'output_filename': 'scripts1.js',
}
}
polls.html
{% load compressed %}
{% compressed_css 'pollsX' %}
<div class='red-me'>
<h1> Hi! I'm a templ! </h1>
</div>
style.css
.red-me {
color: red;
}
The generated output for http://127.0.0.1/polls is
<link href="/static/styles1.css" rel="stylesheet" type="text/css" />
<div class='red-me'>
<h1> Hi! I'm a templ! </h1>
</div>
It can not load /static/styles1.css file in the browser. Even, I tested ./manage.py collectstatic without any success. Did I miss something?
Python-3.4 and Django-1.7
Django pipline updates very frequently, so your particular tutorials are outdated already.
But I want to answer on your question anyway, because I just spent couple hours in fixing the same issue with new pipeline, and want to share my solution and hope it will be helpful for someone.
Everything works for:
Django==1.9.1
django-pipeline==1.6.4
settings.py
INSTALLED_APPS = (
.
.
'django.contrib.staticfiles',
'pipeline',
'polls',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE = {
'CSS_COMPRESSOR': 'pipeline.compressors.cssmin.CSSMinCompressor',
'CSSMIN_BINARY': 'cssmin',
'JS_COMPRESSOR': 'pipeline.compressors.slimit.SlimItCompressor',
'STYLESHEETS': {
'pollsX': {
'source_filenames': (
'style.css',
),
'output_filename': 'css/styles1.css',
'variant': 'datauri',
},
},
'JAVASCRIPT': {
'pollsX': {
'source_filenames': (
'script.js',
),
'output_filename': 'js/scripts1.js',
},
}
}
polls.html
{% load pipeline %}
{% stylesheet 'pollsX' %}
{% javascript 'pollsX' %}
<div class='red-me'>
<h1> Hi! I'm a templ! </h1>
</div>
I think you misspelled your css file name.
Instead of using:
<link href="/static/styles1.css" rel="stylesheet" type="text/css" />
Use:
<link href="/static/style.css" rel="stylesheet" type="text/css" />