So I'm pulling apart a website with the front-end already built and have taken on the task of building out the backend, but I am new to django. I have managed to separate everything out accordingly (css, js, img's in a static folder, html files in a templates folder, etc) and so far have been able to set the index.html as the homepage to django. Within this index.html file, other html files (located in the templates folder along with the index.html file) are being loaded within tags of the index.html file. Currently all of the images, css, and js is coming through in the file, but the html files are not. I am referencing these html files as "name of file.html" However, I cannot seem to get these to load unless I move the templates folder into the static folder (alongside the css, images, js, etc.) and change the reference to "static/templates/name of file.html"
My project setup is as follows. Also I'm running django 1.7.
atmos_v4/
atmos_v4/
init__.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
static/
css/
...
img/
...
js/
...
media/
...
templates/
index.html
...
My urls.py and settings.py are below. I have a feeling my TEMPLATE_DIRS and STATIC_ROOT may be set up incorrectly. If not, would someone be so kind as to tell me what I'm missing? Thank you!
settings.py:
"""
Django settings for atmos_v4 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y=3ey3sv8lm1j358(2bgthtx0bzy_cjaxug#2npx029nfs#5i%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'atmos_v4.urls'
WSGI_APPLICATION = 'atmos_v4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from os.path import join
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
url(r'^admin/', include(admin.site.urls)),
)
index.html reference examples
<div id="wheelartist" style="position:absolute; top:131px; left:536px; z- index:999999;">
<div id="circleartist" class="circleartist">
<a id="homebuttonLink" href="artist_profile.html"><img id="homebutton" title="Home" src="/static/img/icons/user.png" alt=""></a>
<a id="msgsbuttonLink" href="messages.html"><img id="msgsButton" title="Messages" src="/static/img/icons/mail.png" alt=""></a>
<a id="directorybuttonLink" href="directory.html"><img id="directoryButton" title="Directory" src="/static/img/icons/book.png" alt=""> </a>
<a id="cartbuttonLink" href="shopping_cart.html"><img id="cartButton" class="shopingCart" title="Shopping Cart" src="/static/img/icons/shopping.png" alt=""></a>
<a id="contestsbuttonLink" href="contests_list.html"><img id="contestsButton" class="planet" title="Planet" src="/static/img/icons/planet.png" alt=""></a>
<a id="pointsbuttonLink" href="points.html"><img id="pointsButton" class="awards" title="Awards" src="/static/img/icons/awards.png" alt=""></a>
<a id="prefbuttonLink" href="preferences.html"><img id="prefButton" class="tools" title="Tools" src="/static/img/icons/tools.png" alt=""></a>
<a id="searchbuttonLink" href="search.html"><img id="searchButton" class="headphones" title="Search" src="/static/img/icons/music.png" alt=""></a>
<a id="mapbuttonLink" href="artist_careermap.html"><img id="mapButton" title="Career Map" src="/static/img/icons/map.png" alt=""></a>
<a id="profitsbuttonLink" href="artist_profits.html"><img id="profitsButton" title="Profits" src="/static/img/icons/profits.png" alt=""></a>
<a id="statsbuttonLink" href="artist_stats.html"><img id="statsButton" title="Stats" src="/static/img/icons/stats.png" alt=""></a> </div>
templates/
index.html
try to change to this structure
templates/
atmos_v4/
index.html
and inside the settings.py remove this
"from os.path import join"
EDIT: after you update your file now i see that you have bad index.html file, you need to use the built-in function for templates and url
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#url
Related
When I load my local site I cannot get the CSS files to load. I'm running Django 1.9 and python 3.4.2.
Here is my structure:
apps/
app1/
app2/
etc.
clients/
media/ #css, js, images, etc.
static/ #static files
templates/ #html templates
__init__.py
manage.py
settings.py
etc.
In my settings.py file I have:
STATIC_ROOT = os.path.join(BASE_DIR, 'clients', 'static')
STATIC_URL = 'clients/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'clients', 'media'),
]
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'clients', 'media')
And my html template that is calling the css files is as so:
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/primary_stylesheet.css' %}" />
I continue to get a 404 error that says it can't find the css file in:/clients/static/css/primary_stylesheet.css
In my settings.py file I have printed out my STATICFILES_DIRS and STATIC_ROOT and they both lead directly where they should. I've read through the documentation and tried multiple variations of DIRS and ROOT and don't understand why the css file is not pulling correctly - even "collectstatic" is collecting correctly.
I greatly appreciate any help and wisdom someone else has to give.
Thank you!
If you have DEBUG = True set then django won't actually pull your files from the /static/ folder - it finds and collects your staticfiles at runtime when you input the runserver command.
I think you'll find that if you use the default setting for STATICFILES_FINDERS your app will be able to serve your files:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
If you are running your server with python ./manage.py runserver, you need to set urls for both static and media files, check here: https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development
When I am starting a new project, I generally set my urls.py like this:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
url_patterns = [
url(r'^admin/', admin.site.urls),
# your url patterns go here
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This requires you to set STATIC_ROOT, STATIC_URL, MEDIA_ROOT and MEDIA_URL in your settings.py:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static_files'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I'm new to Django and I'm trying to understand how django deals with static files. I'm working on building a blog website following a tutorial. here is my project layout:
-myblog
-manage.py
-myblog
-settings.py
-urls.py
-blog
-views.py
-urls.py
-views.py
-static
-blog
-css
-style.css
-templates
-blog
-blog.html
-static
-css
-style.css
-templates
-index.html
but the index.html file can't find it's css file, in index.html file, I have
{% load staticfiles %}
<link href="{% static 'css/style.css' %}" rel="stylesheet">
but it can find the css file in app directory
{% load staticfiles %}
<link href="{% static 'blog/css/style.css' %}" rel="stylesheet">
my settings.py file:
"""
Django settings for myblog project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'blog/templates'),
)
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myblog.urls'
WSGI_APPLICATION = 'myblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myblog',
'USER': 'root',
'PASSWORD': 'q',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'US/Eastern'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
#
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
# os.path.join(BASE_DIR, 'static/'),
os.path.join(BASE_DIR, 'blog/static/'),
)
can anyone tell me what's going on here? Thanks in advance!
You can have as many static files folders as you want, just a)namespace those folders accordingly (static files for the whole project and for an every app separately) and b) provide the path to your static folders within settings file.
In most up-to-date django (1.8) project I have the following settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'app_name_here/static/'),
os.path.join(BASE_DIR, 'static/'),
os.path.join(BASE_DIR, 'static/bootstrap-3.3.4'),
)
no STATIC_ROOT defined.
Django can't detect the directories out from your project folder. If you keep the static and templates folder in myblog it will work smoothly.
-myblog
-myblog
-settings.py
-urls.py
-blog
-views.py
-urls.py
-views.py
-static
-blog
-css
-style.css
-templates
-blog
-blog.html
-static
-css
-style.css
-templates
-index.html
I wanted to include an ecommerce portal on my website and I have done everything as given on the "Create your Shop page" as given in Django-Oscar documentation, just that in
urls.py instead of
url(r'', include(application.urls)),
I have added
url(r'^buy/', include(application.urls)),
but the problem is that when I hit the url it is neither showing anything nor giving an error.
Any idea what could be the problem?
It could be some urls are clashing or something else trivial but I am not able to understand from where to start debugging.
File urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from view import AboutusView, TwentySevenView
import apps.users.views
from django.conf import settings
#oscar urls
from oscar.app import application
admin.site.site_header = ''
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'torquehp.views.home', name='home'),
# url(r'^users/', include('users.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', include(admin.site.urls)),
url(r'^about-us/$', AboutusView.as_view(), name="about-us"),
url(r'^24x7/$', TwentySevenView.as_view(), name="24x7"),
url(r'^$', apps.users.views.user_home, name="home"),
url(r'^markdown/', include('django_markdown.urls')),
url(r'^users/', include('apps.users.urls')),
url(r'^doorstep/', include('apps.doorstep.urls')),
url(r'^cars/', include('apps.cars.urls')),
url('', include('social.apps.django_app.urls', namespace='social')),
# urls for zinnia
url(r'^blog/', include('zinnia.urls', namespace='zinnia')),
url(r'^comments/', include('django_comments.urls')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, }),
# oscar URLs
url(r'^buy/', include(application.urls)),
)
File settings.py
import os
import sys
from oscar import get_core_apps
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from oscar.defaults import *
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x)
# sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # to store apps in apps/ directory
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'apps.users',
'apps.doorstep',
'apps.cars',
'django_markdown',
'social.apps.django_app.default',
'django.contrib.sites',
'django_comments',
'mptt',
'tagging',
'zinnia',
'compressor',
] + get_core_apps()
# specifying the comments app
# COMMENTS_APP = 'zinnia_threaded_comments'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'oscar.apps.basket.middleware.BasketMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
# Authentication backend used by python-social-auth
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
'oscar.apps.customer.auth_backends.EmailBackend',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"social.apps.django_app.context_processors.backends",
"social.apps.django_app.context_processors.login_redirect",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.i18n",
"django.core.context_processors.request",
"zinnia.context_processors.version",
"django.core.context_processors.debug",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
'oscar.apps.search.context_processors.search_form',
'oscar.apps.promotions.context_processors.promotions',
'oscar.apps.checkout.context_processors.checkout',
'oscar.apps.customer.notifications.context_processors.notifications',
'oscar.core.context_processors.metadata'
)
# TEMPLATE_LOADERS = (
# 'app_namespace.Loader',
# )
ROOT_URLCONF = 'torquehp.urls'
WSGI_APPLICATION = 'torquehp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "",
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306'
}
}
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOGIN_URL = '/users/login/'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates').replace('\\', '/'),
location('templates'),
OSCAR_MAIN_TEMPLATE_DIR,
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
)
REGISTRATION_INVALID = 50
MESSAGE_TAGS = {
REGISTRATION_INVALID: 'InvalidDetails',
}
# temporary , should not be in settings file
SOCIAL_AUTH_FACEBOOK_KEY = ""
SOCIAL_AUTH_FACEBOOK_SECRET = ""
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ""
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ""
LOGIN_REDIRECT_URL = '/blog/'
# ------------------------------------ #
# Settings for sending email #
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# ------------------------------------ #
# site id for django sites framework
SITE_ID = 1
# configuration settings for django-zinnia
ZINNIA_PING_EXTERNAL_URLS = False
ZINNIA_SAVE_PING_DIRECTORIES = False
ZINNIA_MARKUP_LANGUAGE = 'markdown'
ZINNIA_UPLOAD_TO = 'uploads/zinnia/'
# TimeZone Settings
USE_TZ = True
# ------------------------ #
# django s=oscar search settings
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
Screenshots:
http://localhost:8000/buy/
http://localhost:8000/buy/catalogue/
I see that in your second screenshot localhost:8000/buy/catalogue/ you actually get a result. It would seem as if you haven't defined your own templates or somehow need to fix your TEMPLATE_DIRS or TEMPLATE_CONTEXT_PROCESSORS settings.
I haven't used oscar, but that fact that you get something on screen seems like a template loading issue to me.
See their docs about setting the template_context_processors
Can you post your settings please?
Update:
After seeing your settings, the template_context_processors look correct. I next looked at oscar's templates and they seem to extend without qualifying the oscar directory. For example, layout.html (/oscar/templates/oscar/layout.html) does this:
{% extends 'base.html' %}
Now, if you also have a 'base.html' file in your own project directory, say project_dir/templates/base.html, then it'll probably use that instead. Can you try to temporarily rename that file (if it exists) and see what happens?
urls.py
url(r'^buy/', include("app.urls")),
Then under your app directory create a file called urls.py
app/urls.py
# this is your “http://localhost:8000/buy/”
url(r'^$', ViewName.as_view(), name="thename"),
In app/urls.py add the following line:
url(r'^$',views.index,name='index'),
This will redirect you to the index function in app/views.py
In app/views.py do something like that:
def index(request):
#Your logic here
return render(request,'urpoll/index.html'{'category':categorys,'ques':ques,'url':url})
This will render index.html with categories,ques,url. In index.HTML so something like that:
{{ if category }}
{{ category }}
{{ endif }}
I hope this will help.
Maybe you have a naming collision with templates. Django's default template loader, which I assume you're using, can be a bit unintuitive. When you ask it for a template with a given name, it goes through your INSTALLED_APPS tuple in settings in order, checking in each one for a templates folder. If there are two templates with the same path in two different apps, it will always take the first one it finds.
That's why the recommendation in django docs is to 'namespace' your templates by keeping them all in another folder with the name of your app, within the templates folder. Oscar does this, so their templates are in oscar/templates/oscar, so they shouldn't be colliding with any other apps, but I'm wondering if maybe you put an 'oscar' folder within the templates of one of your apps, possibly clashing with base.html.
The problem is that django-oscar is not meant to be included under a sub-path, such as /buy/. In their documentation, their example shows installing it as:
url(r'', include(application.urls)),
If you look at the source of get_urls(), which provides the return value for application.urls, you can see that it does not provide a urlpattern to match r'^$', which is what you would need to match at the URL you are trying to view.
In short, you should follow exactly what the documentation recommends, or you will get unexpected results.
I have been following along with a YouTube tutorial and even though I follow along exactly as he does it, I get the 404 error below. I have also been having no luck getting data from models into my templates. Even if the template loads, it will just come through as blank. ( I can upload an example of this as well) It loads static content but not dynamic content from the database. Anyone know why this may be? I have a guess it might be something in my settings.py? Thank you!
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/band/
My project is setup like this:
atmos_v4/
atmos_v4/
init__.py
settings.py
urls.py
wsgi.py
band/
__init__.py
admin.py
models.py
urls.py
views.py
db.sqlite3
manage.py
static/
css/
...
img/
...
js/
...
media/
...
templates/
band/
band.html
My band/models.py file:
from django.db import models
import datetime
class Band(models.Model):
name = models.CharField(max_length=100, unique=True)
date_added = models.DateTimeField(default=datetime.datetime.now())
date_founded = models.DateTimeField(null=True, blank=True)
image = models.CharField(max_length=1000, null=True, blank=True)
My band/view.py file:
from django.shortcuts import render_to_response
from django.template import RequestContext
from band.models import Band
def band(request, band_id):
band = Band.objects.get(pk=band_id)
return render_to_response('band/band.html', {'band':band}, RequestContext(request))
My band/urls.py file:
from django.conf.urls import *
urlpatterns = patterns('',
url(r'^(?P<band_id>\d+)/$', 'band.views.band'),
)
my atmos_v4/urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
.
.
.
(r'^band/', include('band.urls')),
)
My band.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<h1>{{ band }}</h1>
<body>
</body>
</html>
My settings.py file:
"""
Django settings for atmos_v4 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y=3ey3sv8lm1j358(2bgthtx0bzy_cjaxug#2npx029nfs#5i%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'beer',
'band',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'atmos_v4.urls'
WSGI_APPLICATION = 'atmos_v4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from os.path import join
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
You're going to the URL "/band/" in your browser, but you haven't defined a urlpattern for that URL: you've defined "/" and "/band/<id>/". Either go to the root page, or find the ID of an existing band object and go to that page.
You would almost certainly be better off doing the official Django tutorial, rather than following a random YouTube video.
All, i am using Django1.4,i have a question regarding accessing the img files,js files etc... I have my files in the directory /opt/lab/labsite/media/img for images and /opt/lab/labsite/media/js for javascript files.What should i change the settings in the setting files such that the below html works..I am using django server to run the code
My code is currently located in /opt/lab/labsite/settings.py and other modules lies in /opt/lab/labsite/.........
<img src="/media/img/logo.jpg" alt="logo" />
Below are the settings in the settings.py file
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/opt/lab/labsite/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/opt/lab/labsite/media/'
Changes
MEDIA_ROOT = '/opt/lab/labsite/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/opt/lab/labsite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'labsite.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'labssite.wsgi.application'
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.
'/opt/lab/labsite/templates'
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth'
)
HTML:
<img src="{{ STATIC_URL }}img/hi.png" alt="Hi!" />
<img src="/static/img/hi.png" alt="Hi!" />
<img src="/media/img/hi.png" alt="Hi!" />
<img alt="Hi!" src="/opt/ilabs/ilabs_site/media/img/hi.png">
STATIC_URL you have set doesn't look good. I think that should be STATIC_ROOT.
You should set (for example) MEDIA_URL='/media/' and STATIC_URL='/static/' and I hope you have also enabled static file serving in urls.py
Set this in settings.py:
STATIC_ROOT = '/opt/html/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/opt/lab/labsite/static/',
)
add this in context processors:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
...
)
and don't forget this in INSTALLED_APPS:
'django.contrib.staticfiles',
and then:
<img src="/static/img/logo.jpg" alt="logo" />
or
<img src="{{ STATIC_URL}}img/logo.jpg" alt="logo" />
if logo.jpg is located in /opt/lab/labsite/static/img/
In addition, STATIC_ROOT serves as a static folder to be served by Web servers/reverse proxies like Apache, Nginx, etc. If you invoke:
python manage.py collectstatic
This will copy all files from /opt/lab/labsite/static/ to STATIC_ROOT - /opt/html/static/. This is useful for deployments.
But all this is for development. For production there are better ways to serve static content - https://docs.djangoproject.com/en/dev/howto/static-files/#staticfiles-production