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
Related
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 }}
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.
Since I started using the Django framework I noticed that the CSS style did not appear when I entered the admin site and others templates and I thought it was normal but with the passage of time I have seen that the applications of my partners did have the style, so I copied their projects on my laptop and I ran them and I could see the CSS style of their applications.
I'm getting data from a database from a server, that's the only difference in how my partners and I have been working.
Does anyone know how I can fix this?
PD: I'm working with version 1.8 of Django and version 3.4.4 of python
This is my base of my HTML's code
{% load staticfiles %}
<html>
<head>
<title>DENUE INEGI</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/crm.css' %}">
</head>
<body>
<div class="page-header">
{% if user.is_authenticated %}
{% else %}
<span class="glyphicon glyphiconlock"></span>
{% endif %}
<h1>Directorio Estadístico Nacional de Unidades Económicas INEGI</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
Here is my setting.py file
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',
],
},
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
LOGIN_REDIRECT_URL = '/'
I appreciate your answers, thank you :)
Try to change Debug = True in your application settings and then check the admin panel.
According to this documentation to serve static files during development you have to:
1) define STATIC_URL in settings file - you have it. So you have to create static folder in the root of your project.
2) STATIC_ROOT = os.path.join(BASE_DIR, 'static')
3) In urls.py of you project you have to have this snippet:
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
]
+ static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If your project under deployment, then you can serve static files by the web server. Then you don't need snippet in urls.py
Hope it helps you
Check your urls.py with urls.py of your friends project. I had the same problem with CSS files. and found answer in the docs https://docs.djangoproject.com/en/1.8/howto/static-files/#serving-static-files-during-development
I know this is asked and answered several times but I basically went over all the post on stack overflow and still couldn't get this to work. Right now I am just trying simply change the admin site title. I have the following:
#base_site.html
{% extends "admin/base_site.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('NEW TITLE') }}{% endblock %}
{% block branding %}
<h1 id="site-name">{{ site_header|default:_('NEW TITLE') }}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
And I tried to put this in
my_site/templates/admin/base_site.html,
my_site/templates/admin/my_app/base_site.html, and
my_site/my_app/templates/admin/base_site.html,
but none of these work.
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
I also tried just directly changing django\contrib\admin\templates\admin\base_site.html but still nothing happens.
I am really frustrated now and definitely could use some help, thanks
Updates:
Actually I found out that the local template does have effect.
Like here, the topmost white bar displays "#base_site.html!!##" which is what I put in my_site/templates/admin/base_site.html as a comment by chance. So it kinda working, but I still don't understand why I can't change the site title.
Add your Django app above 'django.contrib.admin' in settings -> INSTALLED_APPS. The order of apps in INSTALLED_APPS matters.
# settings.py
...
INSTALLED_APPS = [
"your_app.yourAppConfig", # add your app here
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
...
use my_site/my_app/templates/admin/base_site.html
put your app where you define this template before
'django.contrib.admin', in INSTALLED_APPS
source link
First open your settings.py and add a template folder:
TEMPLATES = [
{
'DIRS': [
'/path/to/your/django-project/templates', # Absolute Path
# os.path.join(BASE_DIR, 'templates') # Relative Path
],
...
Then move the file base_site.html to the following directory.
It's important to keep the structure on the file system.
/path/to/your/django-project/templates/admin/base_site.html
Content of base_site.html:
{% extends "admin/base_site.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('NEW TITLE') }}{% endblock %}
{% block branding %}
<h1 id="site-name">Your new Title</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
Django Documentation - Overriding Admin Site
Hope that helps.
So you should delete including the curly braces, and just write the text you want.
Remove: `{{ site_title|default:_('NEW TITLE') }}` Write: NEW TITLE
Remove: `{{ site_header|default:_('NEW TITLE' }}` Write: NEW TITLE
Also be sure that you placed the folders (templates/admin) in the root directory of your project. root directory is the container for all your app folders and also the manage.py file.
In other words, "templates" folder you want to create should be at the same level with manage.py file.
Your folder structure should look like this:
mysite/
templates/
admin/
base_site.html
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
...
...
I am not sure if I understand right. but you can easy to change the title by doing this:
in the "urls.py" file
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
.......
]
admin.site.site_header = 'My New Title'
admin.site.site_title = 'My New Title'
Then it should get the job done for you.
To change Django Admin site title, you can add these two lines in the admin.py of your Django app:
from django.contrib import admin
# change Django admin title
admin.site.site_title = 'My Blog Admin'
# change Django admin site header
admin.site.site_header = 'My Blog Admin'
just getting started in Django, and I have some problems with the inheritances. It just seems that the loop for doesn't work when inheriting other template. Here's my code in base.html:
<!DOCTYPE html>
<html lang="es">
<head>
<title>{% block title %}Titulo del proyecto web{% endblock %}</title>
</head>
<body>
<div id="header">
<h1>Título del proyecto web</h1>
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
So here in the index.html the objective is to show the for loop and also the 'header' div of base. Index.html is this:
{% extends "base.html" %}
{% block title %}Questions{% endblock %}
{% block content %}
{% for pregunta in preguntas %}
<h3>{{ pregunta }} ?</h3><br/>
{% endfor %}
{% endblock %}
I've checked the code several times. If I quit the inheritance the loop works fine, but I don't know why it doesn't work when extending to base.html.
When I run the server page it just appears a blank page. Help would be highly appreciate. Thank you very much.
EDIT: Here it is my template directories structure:
Main Project/Templates/ and inside Templates folder there's the base.html and a 'preguntasyrespuestas' folder which is the app name.
And inside 'preguntasyrespuestas' folder there is the index.html template. But it automatically creates a 'base.html' also inside this folder (?) I just delete it.
And the views.py code is that shown here:
from django.http import HttpResponse,Http404
from preguntasyrespuestas.models import Pregunta
from django.shortcuts import get_object_or_404, render_to_response
def index(request):
preguntas = Pregunta.objects.all()
return render_to_response('preguntasyrespuestas/index.html',
{'preguntas': preguntas})
def pregunta_detalle(request, pregunta_id):
pregunta = get_object_or_404(Pregunta, pk=pregunta_id)
return render_to_response('preguntasyrespuestas/pregunta_detalle.html',
{'pregunta': pregunta})
Here's the settings.py template var:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["C:/Projects/primerproyecto/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',
],
},
},
]
So, must both files (base.html and index.html) be in the Templates directory (not inside the app directory inside templates)? I've tried it and still happens the same (output a blank page), if not an error while trying to combine files locations (between theses two folders).
In your app the template folder structure must be something like:
|- preguntasyrespuestas # your app folder
|- templates
-base.html
|- preguntasyrespuestas
-index.html
-pregunta_detalle.html
....
Templates directory must be in your app folder and inside it must be another folder with the name of your app and inside this must be the template files.
EDIT
If your templates are in the app template folder you should change DIRS to an empty list: DIRS:[]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], # change here: put an empty list
'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',
],
},
},
]