I just started learning Django. I followed the guide on the Django webpage, but still don't feel that understood it. So I decided to make something similar by myself. Basically I am making similar voting system as in guide, but a bit different. So I started doing it by reading some documentations and guide text. I created a generic listview to display index.html, which will show the list of votings. '
this is my views code:
class IndexView(generic.ListView):
template_name = 'Vote/index.html'
model = Type
def get_queryset(self):
return Type.objects.order_by('-pub_date')
here is my index.html code:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'Vote/style.css' %}" />
{% block content %}
<h2>Votings</h2>
<ul>
{% for voting in object_list %}
<li>{{ voting.Type_name }}</li>
{% empty %}
<li>Sorry, there are not votes.</li>
{% endfor %}
</ul>
{% endblock %}
Models code:
from django.db import models
from django.utils import timezone
# Create your models here.
class Voted_Object(models.Model):
Voted_Object_name = models.CharField(max_length=50)
Voted_Object_image = models.ImageField
Voted_Object_rating = models.IntegerField(default=0)
class Type(models.Model):
pub_date = models.DateTimeField
Type_name = models.CharField(max_length=50)
Urls code:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
#url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
# url(r'^(?P<pk>[0-9]+)/voting/$', views.VoteView.as_view(), name='voting'),
]
There is also settings for templates:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR],
'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',
],
},
},
]
this is my directory:
and finally this is the error:
TemplateDoesNotExist at /Vote/
Vote/index.html, Vote/type_list.html Request Method: GET Request
URL: http://127.0.0.1:8000/Vote/ Django Version: 1.8.2 Exception
Type: TemplateDoesNotExist Exception Value: Vote/index.html,
Vote/type_list.html Exception
Location: C:\Users\Vato\Envs\django_test_env\lib\site-packages\django\template\loader.py
in select_template, line 76 Python
Executable: C:\Users\Vato\Envs\django_test_env\Scripts\python.exe
Python Version: 2.7.10 Python Path:
['C:\Users\Vato\PycharmProjects\Project3',
'C:\Users\Vato\PycharmProjects\Project3',
'C:\windows\SYSTEM32\python27.zip',
'C:\Users\Vato\Envs\django_test_env\DLLs',
'C:\Users\Vato\Envs\django_test_env\lib',
'C:\Users\Vato\Envs\django_test_env\lib\plat-win',
'C:\Users\Vato\Envs\django_test_env\lib\lib-tk',
'C:\Users\Vato\Envs\django_test_env\Scripts',
'C:\Python27\Lib', 'C:\Python27\DLLs',
'C:\Python27\Lib\lib-tk',
'C:\Users\Vato\Envs\django_test_env',
'C:\Users\Vato\Envs\django_test_env\lib\site-packages']
It asks for 2 templates one index.html which I have and I wrote and second for type_list.html
I think the error is caused by missing file of type_list.html, but I don't get why django asks me for that template. Where in the code do I specify the need for it? and How can I fix it so that the program will get votes from database and display them on index?
as I researched and as I understand second template is looked because of model(Type)-to lower case and _list ending for some reason. it is made somewhere automatically, but I don't understand it.
I am not sure in my code, cause much is copied from documentations, but as I thought it should have worked without the second(type_list) template. Sorry for the long post. Thought shouldn't miss any code.
If you have any suggestions for the better way of learning django please feel free to comment.
You have 'DIRS': [BASE_DIR], but your templates are not in BASE_DIR, they are in BASE_DIR/templates. You should have:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
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 facing one issue. I am trying to implement login/logup application using Django but in login page I am getting the below error.
TemplateDoesNotExist at /login/
login.html
Request Method: GET
Request URL: http://127.0.0.1:8000/login/
Django Version: 1.11.2
Exception Type: TemplateDoesNotExist
Exception Value:
login.html
Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/loader.py in select_template, line 53
Python Executable: /usr/bin/python
Python Version: 2.7.6
I am explaining my login.html page below.
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock %}
urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),
url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'),
]
Please help me to resolve this error.
Set template dir path in settings.py
os.path.join(BASE_DIR, 'templates')
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.template.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Your project structure:
project
|---- project
|---- templates
|----- static
I think you need to set your TEMPLATES DIRS in your settings.py like this:
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates/ariticle'), ], # define your template dir
...
},
]
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',
],
},
},
]
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