TemplateDoesNotExist when running django app - python

My django app is structured as below
home/damon/dev/me/myproject/
manage.py
/mytracker/
__init__.py
settings.py
urls.py
/monitor/
/media/
/mymonitor/
__init__.py
models.py
views.py
urls.py
/templates/
base.html
home.html
In .bashrc I set PYTHONPATH as /home/damon/dev/me/myproject/
and in settings.py added these values for MEDIA_ROOT and TEMPLATE_DIR
MEDIA_ROOT = 'home/damon/dev/me/myproject/mytracker/monitor/media'
MEDIA_URL = '/site_media/'
TEMPLATE_DIRS = (
'home/damon/dev/me/myproject/mymonitor/templates'
)
mytracker.urls.py has
url(r'',include('mymonitor.urls')),
url(r'^site_media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.MEDIA_ROOT}),
whereas mymonitor.urls.py has
...
url(r'^$','mymonitor.views.home',
{'template_name':'home.html',
'page_title':'Home'
},
name='home'),
..
The base.html is extended by home.html
{% extends "base.html" %}
{% block content %}
Your Home
{% endblock %}
I think the pythonpath,locations of files everything is correctly done..Still I am getting a TemplateDoesNotExist error
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.4
Exception Type: TemplateDoesNotExist
Exception Value:
[{'page_title': 'Home'}, {'csrf_token': <django...
The views.py has
def custom_render(request,context,template):
req = RequestContext(request,context)
return render_to_response(req)
def home(request,template_name,page_title):
context = {'page_title':page_title}
return custom_render(request,context,template_name)
I cannot figure out why this occurs.How do I diagnose this error..? Can someone please tell me?

It should be render_to_response(template) instead of render_to_response(req).
Here is a snippet from Django documentation:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
Also you have a relative path in TEMPLATE_DIRS when it should be absolute (that is, starting from a slash, like /home/damon/...). Because of this filesystem.Loader doesn't find your template.
And here is just an advice. TemplateResponse is much more awesome and cool then old-school render_to_response.

You should not modify TEMPLATE_DIRS in this case, because app_directories.Loader (enabled by default) should do it for you, if you have your application in INSTALLED_APPS.
You probably forget '/' in the path in TEMPLATE_DIRS ('home/...' instead should be '/home/...')
Your TEMPLATE_DIRS as you have it now is just string (in parentheses where the parentheses are ignored here), it should be a tuple so you need to add comma after your path:
TEMPLATE_DIRS = (
'/home/damon/dev/me/myproject/mymonitor/templates',
)

Related

Django 1.11 404 Page while Debug=True

Without making things difficult, I just want to show a special 404 render with staticfiles.
If you set DEBUG = False you can use in urls.py
handler404 = 'app.views.handler404'
But it is without staticfiles. I don't want to install a web server for a simple app.
With DEBUG = True in urls
url(r'^404/$', views.handler400)
is not overriding the default Page not found (404) page.
What is the easy way to achieve a render e.g. when you type localhost/asdfhjfsda with staticfiles when DEBUG=True?
Thanks in advance...
Easiest way to do this post Django 1.9 is in your urls.py:
from django.views.defaults import page_not_found
url(r'^404/$', page_not_found, {'exception': Exception()})
It wants an exception, give it an exception :)
In django 1.10 docs:
Changed in Django 1.9:
The signature of page_not_found() changed. The function now accepts a second parameter, the exception that triggered the error. A useful representation of the exception is also passed in the template context.
Have a look at your 'app.views.handler404' definition, it might miss a parameter, and maybe it's that why the r'^404/$'handler doesn't provide you with the correct method invocation.
I have a complete solution
My development environment:
Windows 7, Python 3.5.2, Django 1.11, WAMP 3.0.6 (Apache 2.4.23, mod_wsgi)
Suppose you have error_404.html template with static files
Create next directory structure ("mysite" - Django project root folder)
mysite\
mysite\
settings.py
urls.py
views.py
static\
error404\
files\
style.css
image.jpg
templates\
error404\
error_404.html
mysite\mysite\settings.py
import os
DEBUG = False
TEMPLATES = [{
..
'DIRS': [os.path.join(BASE_DIR, 'templates')],
..
}]
STATIC_URL = '/static/'
STATIC_ROOT = 'FullPathToYourSite.com/mysite/static/'
mysite\mysite\urls.py
from django.conf.urls import handler404, handler500
from . import views
urlpatterns = [..]
handler404 = views.error_404
handler500 = views.error_404
mysite\mysite\views.py
from django.shortcuts import render
def error_404(request):
return render(request, 'error404/error_404.html')
Some Jinjo logic in "error_404.html" (pseudocode)
{% load staticfiles %}
...
link type="text/css" href="{% static 'error404/files/style.css' %}"
...
img src="{% static 'error404/files/image.jpg' %}"
...

Why won't Django load my static CSS files?

I'm having trouble getting Django to load my CSS for my html template. I'm aware that there are a lot of posts like this, such as here and here, but I'm not sure what else to do here as I've tried several of these types of these solutions to no avail.
Loading up my website using python manage.py runserver returns this log:
[31/Jul/2016 01:58:29] "GET / HTTP/1.1" 200 1703
[31/Jul/2016 01:58:29] "GET /static/css/about.css HTTP/1.1" 404 1766
I'm not sure if the 404 on the end of the second line of the log refers to a 404 error or not.
I have tried adding the static files to my urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='about.html'))
]
urlpatterns += staticfiles_urlpatterns()
I have tried modifying my settings.py:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIR = os.path.dirname(os.path.abspath(__file__)) + "/static/"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder'
)
And I of course used the proper loading methods in the actual template itself:
{% load staticfiles %}
...
<link rel="stylesheet" href="{% static 'css/about.css' %}">
Here's my file structure:
Personal_Website
|Personal_Website
||settings.py
||urls.py
||etc...
|static
||css
|||about.css
Frankly, I'm not sure what else to do here. I feel like I've tried everything with the settings and still I'm getting that same log.
You should have this to serve static file in project directory...
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]
os.path.dirname(os.path.abspath(__file__)) This is pointing to Personal_Website folder where settings all file is there...

Django: MEDIA_URL not set in template

I've read a lot of question and article but can't find what I'm missing.
Here is my conf :
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__),'static').replace('\\', '/'),
)
urls.py
urlpatterns = [
url(r'^$', include('home.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^artist/', include('artists.urls')),
url(r'photo/', include('photo.urls'))
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Whatever, my media are served, cause when I go to http://localhost:8000/media/path/to/image.jpg, i have my image.
But when in template I go like this :
<img class="avatar secondary-content" src="{{MEDIA_URL}}{{artist.artist_image}}">
I only have the image path. When I change in html {{MEDIA_URL}} by '/media/', it works.
So it seems my MEDIA_URL is not set in template and as far as I've searched, I can't see what I missed.
I'm on django 1.8.2. If you need any informations, just ask me.
You need to define the django.template.context_processors.media template context processor in your settings for MEDIA_URL variable to be present in the template context.
If this processor is enabled, every RequestContext will contain a
variable MEDIA_URL, providing the value of the MEDIA_URL setting.
Including this in your settings will include MEDIA_URL in the template context. It is not included by default in Django 1.8 settings. We need to set it explicitly.
context_processors = [
...
'django.template.context_processors.media', # set this explicitly
]
models.ImageField has a property called url which gives you the browsable path of your image.
You should be using artist.artist_image.url instead of prepending MEDIA_URL to your image name manually:
<img class="avatar secondary-content" src="{{artist.artist_image.url}}" />
--
Make sure artist_image is not None, otherwise calling .url throws an exception.

Where are template tags include files expected to be found in Django framework

I'm having trouble including within a template thats it. I cannot find in the documentation where the include goes to look for the included .html (I assumed it would be the same as the templates?), I'm putting {% include "xy.html" %} in one file, but it looks like xy.html is not being found. I can't find any error returned either. xy.html is in the same directory as its calling file which is in a template folder in Django parlance.
I get no error message displayed, I simply dont get the included file displayed.
Where should I place the xy.html file?
According to the include documentation:
The template name can either be a variable or a hard-coded (quoted)
string, in either single or double quotes.
Put the template name into quotes:
{% include "xy.html" %}
FYI, xy.html should be anywhere inside TEMPLATE_DIRS directories.
FYI2, setting TEMPLATE_DEBUG setting to True would help to see the detailed error message in case of an exception raised while rendering the template.
Let's use an example project called foo:
foo
-blog
-admin.py
-models.py
-views.py
-tests.py
-templates
-blog
-post.html
-news
-admin.py
-models.py
-views.py
-tests.py
-templates
-newsitem.html
-foo
-settings.py
-urls.py
-wsgi.py
-templates
-base.html
-blog
-post.html
If your settings.py includes:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates')
)
Then Django overrides app templates with the TEMPLATE_DIRS template, this means that if a post.html resides both in blog/templates/blog/post.html and templates/blog/post.html (as the above example)
then Django will load the later.
If you don't specify a TEMPLATE_DIRS then Django searches for the post.html within the templates folder of each app, this means that if you specify a: blog/templates/blog/post.html and a news/templates/blog/post.html both are valid,
in this occasion Django will load the template depending on how you INSTALLED_APPS looks like:
INSTALLED_APPS = (
...
'blog',
'news',
...
)
Then Django will render the template of the blog app instead of the template of news app (if we had a blog/post.html under the templates of news).
Yet if your INSTALLED_APPS looks like:
INSTALLED_APPS = (
...
'news',
'blog',
...
)
Then Django will load post.html from the news app rather than blog app (again if we had templates/blog/post.html under our news app).
You should also be picky about template names, templates with similar names will override each other depending on your settings and INSTALLED_APPS order (higher overrides lower), TEMPLATE_DIRS templates always override all others.

How can I get PyCharm to recognize the static files?

I have one Django project that looks like:
/.idea
/clients
/app
/static
coin.png
/templates
index.html
__init__.py
urls.py
/clients
settings.py
manage.py
In index.html I have (I can see the image on render):
{% load staticfiles %}
<img src="{% static 'coin.png' %}">
Relevant parts of settings.py:
STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), '../static/'),
)
INSTALLED_APPS = (
'django.contrib.staticfiles',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static',
)
In project structure I've added /clients since the root of the Django project is one level up from the repo root. However all my {% static %} uses in this project keep getting highlights as not existing even though Django can find them. Ideas on how to resolve this?
You need to set the following settings, to tell PyCharm where to find the project root:
Django settings to set (image)
You can also use {{STATIC_URL}}/path/to/files, which works different by pycharm
This worked wonders. It is a bit strange of pycharm though.
STATICFILES_DIRS = (
'static',
)
The above assumes that your static dir is called static right under your root. Now need to do os.path.join. I've tried and tested this.

Categories

Resources