Django template does not change when `TEMPLATE_DIRS` is modified - django

I am following the tutorial in the offical documentation https://docs.djangoproject.com/en/1.7/intro/tutorial02/
I am in the section of customizing the templates, but I am running into problems with changing the content of the templates
This is in my settings.py
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
print TEMPLATE_DIRS
Here is my tree structure
└── mysite
├── manage.py
├── mysite
├── polls
└── templates
└── admin
└── base_site.html
I double check the path using print, which should be correct
['/Users/mysite/templates']
and edit the base_site.html to
{% block title %}{{ title }} | {{ site_title|default:_('Poll admin') }}{% endblock %}
However it seems like I cannot see the changes when I rerun
python manage.py runserver
The other questions seems to have a path problem, but I think my path is correct,
http://stackoverflow.com/questions/4921080/how-do-i-change-templates-on-django-admin-pages

Related

How to serve `Docs` folder in Django which contains static html files?

I have following code structure in Django.
├── docs
│   └── _build
│      ├── doctrees
│      └── html
│   └── index.html
│  
├── localcoinswap
├── scripts
├── _static
├── _templates
├── tests
└── manage.py
Here the docs folder contains static html files. i.e index.html
Here are some questions regarding to problem:
The docs folder's html should be served as url <domain>/docs/index.html in Django project. How to achieve this
It should be restricted to User's who have is_staff attribute True.
What urlpattern should I use and Which View is useful to serve those static files (Admin restricted)?
Thank you in advance!
Add the base directory for your docs in TEMPLATES setting in settings.py.
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, '_templates'), "add your base directory here"],
...
}
]
In your urls.py, serve the files using TemplateView. To further restrict the url to only the staff users, you can wrap the view in staff_member_required decorator.
from django.contrib.admin.views.decorators import staff_member_required
...
urlpatterns += [url(r'^docs/index\.html$', staff_member_required(TemplateView.as_view(template_name='index.html')), name="index"),]
Make sure the file names for your templates and doc templates don't clash, else the first one evaluated according to the DIR list will always be considered.

Static does not loads static files in Django

This is my directory structure
app_web
_init_.py
settings.py
urls.py
wsgi.py
upload_app
migrations/
static/
js/
alert.js
templates/
upload.html
_init_.py
admin.py
apps.py
models.py
tests.py
views.py
db.sqlite3
manage.py
In settings.py , my
STATIC_URL = '/static/'
and in my upload.html
{% load staticfiles %}
<script type="text/javascript" src="{% static "js/alert.js" %}"></script>
It does not works and throws 404 error everytime. I even tried load static but it still cannot load anything from static folder and throws 404 error.
I am using Windows 10 machine and Django==1.9
The idea was to create a static directory outside the upload_app folder. The reason is that in the settings.py the BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . That means one directory above is the base directory, so it will start searching static/ from that directory. But it will never find it as I placed inside upload_app/static .
Also, I need to work on putting templates outside the app upload_app as it's not generally best practice to keep templates inside the app.
looking for other suggestions in structure

Where should i put django application folder

I have followed several django tutorials on the web.
There is 2 folders: One for django project and another for application. We can have multiple applications for the same project but i my case, i have just one.
Sometimes, the application folder is located at the same level than project folder and sometimes, the application folder is located inside project folder.
I do not know what is the best solution... It works in both case. It is just a state of the art question
Thanks
Mostly it is a matter of choice and the organization of your Project. Even thought, i will post you here a recomented layout and good reasons to choose this
myproject/
manage.py
myproject/
__init__.py
urls.py
wsgi.py
settings/
__init__.py
base.py
dev.py
prod.py
blog/
__init__.py
models.py
managers.py
views.py
urls.py
templates/
blog/
base.html
list.html
detail.html
static/
…
tests/
__init__.py
test_models.py
test_managers.py
test_views.py
users/
__init__.py
models.py
views.py
urls.py
templates/
users/
base.html
list.html
detail.html
static/
…
tests/
__init__.py
test_models.py
test_views.py
static/
css/
…
js/
…
templates/
base.html
index.html
requirements/
base.txt
dev.txt
test.txt
prod.txt
Allows you to pick up, repackage, and reuse individual Django applications for use in other projects
Environment specific settings. This allows to easily see which settings are shared and what is overridden on a per environment basis.
Environment specific PIP requirements
Environment specific PIP requirements
Small more specific test files which are easier to read and understand.

django not displaying image

I started with a django app and tried displaying an image in the home page. But the image is not getting displayed.
My settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
MEDIA_URL = "/media/"
My urls.py:
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'',include('users.urls')),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My home.html:
<html>
<head>
<title>MY SITE</title>
</head>
<body>
<img src="/media/image/myimage.jpg" alt="my image"/>
Welcome to my site
</body>
</html>
I get the text my image displayed instead of the image
ok, so I set up a simple 'paired-down' working example of this so no moving pieces were missing. Some Notes:
I used django 1.6
If you want to use a 'scale-able' delivery of static images you will want to follow
the django-1.6 staticfiles documentation which is what this example provides.
This means that you need to hack-n-slash your MEDIA references. ( MEDIA is really meant for file upload's) and you dont need to fool with the staticfiles_urlpatterns in your urls.py file. As you get this behavior out-of-the box when you add 'django.contrib.staticfiles' to your settings.py
Overview: Here is what your file tree-layout will look like in django 1.6, and the file structure that I am referencing in this answer.
├── djproj
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py
└─── myapp
   ├── admin.py
   ├── __init__.py
   ├── models.py
   ├── static
   │   └── myapp
   │   └── myimage.jpg
   ├── templates
   │   └── index.html
   ├── tests.py
   └── views.py
Step 1: Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
Step 2: In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
Step 3: change your home.html to look like this ( I used index.html in my example )
[ PROJECT_HOME/myapp/templates/index.html ]
<html>
<head>
<title>MY SITE</title>
</head>
<body>
{% load staticfiles %}
<img src="{% static "myapp/myimage.jpg" %}" alt="My image"/>
Welcome to my site
</body>
</html>
Make sure to read the django-1.6 staticfiles documentation related to STATICFILES_STORAGE so you understand what these template tags are buying you. Hint: python manage.py collectstatic
Step 4: ( you may have already done this, but I did not see it) Make sure that TEMPLETE_DIRS is defined in your settings.py and includes your home.html ( key here is that django's template engine needs to be serving this as we will be using some template tags)
[ PROJECT_HOME/djproj/settings.py ]
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
BASE_DIR + '../myapp/templates',
)
Step 5: build a view that renders your home.html page.
[ PROJECT_HOME/myapp/views.py ]
from django.shortcuts import render_to_response
def index( request ):
return render_to_response('index.html')
Since this is a bit convoluted, and there are several moving pieces here: here is a changeset that shows the complete 'changes'
You can of-coarse pull the entire github project if any of this is confusing.
django-staticfiles-setupexample
Final Note: STATIC files were not always handled this way in django. The MEDIA dir used to be the settings attr you were after. So this answer is for Django 1.6 ( staticfiles were added in django version 1.3)( the directory layout was changed in django 1.5).
You can ( as you were trying to do) hardwire your media dirs to the STATIC defines. Altho I do-not recommend this. Which is why I did not describe how to do it this way.
You are adding the media urls too late in the list. Django will try to match each urlpattern in succession, stopping when it gets to the first one. In this case, it matches on r'' and doesn't get to the static files or the media urls.
You may be able to put each pattern in the single call to patterns(), instead of using +=. That would be the cleanest, but I can't test it here. A sure-fire way to do it would be to pull the "users.urls" line out and add it later, like so:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += url(r'',include('users.urls'))
I'd recommend you set DEBUG = TEMPLATE_DEBUG = True and request the image URL directly.
You'll get Django debug output either showing that the URL can't be matched or the file path it's actually looking for.
The settings look generally correct although you've not shared BASE_DIR which is important in this case.
I had been struggling with the issue for like an entire day yesterday... I finally gave up and moved on creating my site without worrying about the images. Then today I decided to check the responsiveness of the site. I found out that my URLs were okay since I had strictly been following the documentation and best practices. The chrome console was saying:
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
The issue was with HTTP Referral Policy. Check them out. So after doing some research, this helped a lot, I found out that AdBlock was blocking my referred images. Apparently, my /media/ path was flagged in one of their regex patterns, deciding that my images were redirections to Ads. The ironic thing is that my website is about ads... so it must have heavily factored in, as my site has words like 'ad' in its url patterns. Long story short, I disabled AdBlock and my images now render. So I think it might be worth considering that even with best practices in your Django code, such an error could be caused by something with your browser!

django include template from another app

While setting up my project and working to keep apps non-dependent, I've hit a snag. I'd like all of the templates from the different apps to have a consistent header and footer. Here's what I'm trying:
myproject/
base/
templates/
header.html
footer.html
app1/
templates/
my_app1_page.html -> want to include 'header.html'
and 'footer.html' from base app
Pretend there are many more apps that want to do this as well. Is this possible and/or the right way to do it?
As long as the apps are in INSTALLED_APPS and the template loader for apps dirs is enabled, you can include any template from another app, i.e.:
{% include "header.html" %}
... since your templates are located directly in the templates dir of your app.
Generally, in order to avoid name clashes it is better to use:
app1/
templates/
app1/
page1.html
page2.html
app2/
templates/
app2/
page1.html
page2.html
And {% include "app1/page1.html" %} or {% include "app2/page1.html" %} ...
But: for keeping a consistent look and feel, it is so much better to use template inheritance rather than inclusion. Template inheritance is one of the really good things of the Django template system, choose inheritance over inclusion whenever it makes sense (most of the time).
My recommendations:
Have a base template for your project ("base.html" is the default convention) with header and footer and a {%block content%} for your main content.
Have your other templates inherit form base.html {% extends "base.html" %} and override the content section
See another response to this question for links to the doc
While you can certainly do that by using the include tag and specifying absolute paths, the proper way to work in Django is by using Template inheritance.
If you start a project with "$ django-admin startproject project" a folder named "project-folder-name" i.e. project/ is created. After adding a few apps and adding the apps in the "settings.py" -> INSTALLED_APPS=[..., app1, app2] and creating a templates folder within the project/ I got structure like this:
project/
project/
templates/
base.html
app1/
templates/
app1/
page1.html
page2.html
app2/
templates/
app2/
page1.html
page2.html
in template app1/template/page1.html I wrote
{% extends 'base.html' %}
and the "TemplateDoesNotExist at /" Error message appeared.
Then I added another App named "core" and added base.html to the template folder (+edit INSTALLED_APPS in settings.py) and i got this structure now:
project/
project/
templates/ (unused)
base.html (not seen)
core/
templates/
base.html
app1/
templates/
app1/
page1.html
page2.html
[...]
Now the error message disappears and the base.html is found with templates/app1/page1.html:
{% extends 'base.html' %}
You can change the folder structure like this:
core/
templates/
core/
base.html
then you need to change the template app1/page1.html to
{% extends 'core/base.html' %}
as well.
As an alternative you can also add "your-project-name" in this explaination "project" into your settings file like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'project', # your project name main folder
'core',
'App1',
'App2',
]
And now django finds the project/templates/base.html as well. However I don't know if this solution is recommended.
project/
project/
templates/
base.html (now it is found)
P.S. Thanks (my upvotes aren't counted yet) and comment me if this answer was somehow clear and understandable