How to make base template use static files and to make other templates that inherits base template to use same static files?
As I read in django documentation it writes about how to use static files that are used for specific app. But I can't seem to find a way to make it use static files from outside app.
Given app inherits everything, but static files.
My settings.py:
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# 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',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'myproject.apps.finance',
'myproject.apps.base',
'django.contrib.admin',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
This is my current homepage settings:
url for homepage:
from django.conf.urls import patterns, include, url
from myproject.views import hello
urlpatterns = patterns('',
('', hello),
)
view of homepage:
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse
import datetime
def hello(request):
hello = "Hello World"
return render_to_response('home/home.html', {'hello': hello})
homepage template:
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
base template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}/css/style.css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My Personal Finance Site</h1>
{% block content %}{% endblock %}
{% block footer %}
<section class="divider1">
<p>Thanks for visiting my site.</p>
<p>All rights reserved</p>
</section>
{% endblock %}
</body>
</html>
my CSS file is located in empty project called base. But I think there could be better way to use static files that are outside given app.
So what would be the best way to link base template with css file to make other templates that intherits base, to get same css file configuration?
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
{% block css %}
<link rel="stylesheet" href="{{ STATIC_URL }}/css/style.css">
{% endblock %}
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My Personal Finance Site</h1>
{% block content %}{% endblock %}
{% block footer %}
<section class="divider1">
<p>Thanks for visiting my site.</p>
<p>All rights reserved</p>
</section>
{% endblock %}
</body>
</html>
page.html
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block css %}{{block.super}}
//put css here
{% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
settings.py
import os
import sys
..........................
SITE_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(SITE_ROOT, 'app_name'))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'staticfiles'),
)
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.
os.path.join(SITE_ROOT, 'templates'),
)
....................
make sure that the template tag "{% load static %}" is at the top of your .html file. that will load your static folder.
sample
{% load static %}
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block css %}{{block.super}}
//put css here
{% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
Related
when I deploy my django 2.2 app on OVH but the static files like the image is not displayed even though the path is correct
myapp/settings
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_URL = '/static/'
index.html
{% extends 'layout/base.html' %}
{% load static %}
{% block content %}
<img src="{% static 'images/fondu2.png' %}" style="width:500px;height:500px">
{% endblock content %}
myapp/urls.py
.......
from .import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index, name='index'),
]
where is the problem?
I'm trying to style a form in django admin. I created a file to extend the base admin page with myApp/templates/admin/base_site.html and I'm calling in a new css file with:
{% extends 'admin/base.html' %}
{% load static %}
{% block branding %}
{% block extrastyle %}
<link rel='stylesheet' href='{% static 'css/admin.css' %}'>
{% endblock %}
{% endblock %}
I added a static directory and file at myApp/static/admin/css/admin.css. Since the admin app has already took control of URIs like http://127.0.0.1:8000/static/admin/css/base.css my app can't find static/css/base.css because it expects my admin.css to be in venv/lib/python3.9/site-packages/django/contrib/admin/static/admin/css. I want to extend the base css (add to it), not necessarily completely override it.
I'm guessing the answer is to edit settings.py to tell it to look at myApp/static but I'm not sure how. The relevant settings.py lines are:
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static/'),
]
STATIC_URL = 'static/'
Thanks.
I'm learning to make some chat website, and i cannot quite get how to use urls correctly. The problem is that when I get to "http://127.0.0.1:8000/chat", links into the header became like "http://127.0.0.1:8000/chat/main" instead of "http://127.0.0.1:8000/main"
project urls:
from django.contrib import admin
from django.urls import path
from django.urls import include, path
from chat import views as chat_views
from mainapp import views as mainapp_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', mainapp_views.index),
path('chat/', include('chat.urls')),
]
chat app urls:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<str:room_name>/', views.room, name='room'),
]
chat app views:
from django.shortcuts import render
def index(request):
return render(request, 'chat/chatindex.html')
def room(request, room_name):
return render(request, 'chat/room.html', {
'room_name': room_name
})
index.html
<!DOCTYPE html>
{% load static %}
<html>
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"/>
<title>{% block title %}{% endblock title %}</title>
</head>
<body>
<header>
<div class="navbar navbar-dark bg-dark shadow-sm">
Главная
Поиск собеседников
Контакты
FAQ
Регистрация/Вход
</div>
</div>
</header>
<main>
<div>{% block content%}{% endblock content %}</div>
</main>
<footer class="footer mt-auto py-3 bg-light">
<div class="container">
<span class="text-muted">Давай общаться!</span>
</div>
</footer>
</body>
</html>
chatindex.html
{% extends "index.html" %}
{% block title %}Контакты{% endblock title %}
{% block header %}{% endblock header %}
{% block content %}
В какую комнату хотите зайти?
<br>
<input id="room-name-input" type="text" size="100">
<br>
<input id="room-name-submit" type="button" value="Enter">
<script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#room-name-submit').click();
}
};
document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/chat/' + roomName + '/';
};
</script>
{% endblock content%}
I'm pretty sure that the problem is about "path('<str:room_name>/', views.room, name='room')", but i can't understand how to fix it and save opportunity to enter rooms with chat-page.
Thanks a lot!
Very likely you make relative paths. Indeed, if you visit a page like some.domain.com/foo, and the link is link, then it will visit some.domain.com/foo/bar, since that is a relative path: relative to the current path.
You can solve this by specifying an absolute path, which has a leading slash, so:
<!-- ↓ leading slash -->
FAQ
But it is better not to generate URLs manually. If you later for example change the URL paths, you will need to alter all URLs. You can give your views a name, like:
path('faq', views.faq, name='faq')
and in the template work with the {% url … %} template tag [Django-doc]:
<!-- ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ url template tag -->
FAQ
Django will then look for a view with the given name, and automatically generate the corresponding URL.
I have the code below to load static files, but I keep getting a TemplateSyntaxError. Does anyone know how I can fix this issue?
Template:
{% load staticfiles %}
{% load static %}
<img class="logo" alt="Test Pic" src="{% static 'images/logo.png' %}" width="110" height="70">
{% block main %}
{% endblock %}
Settings:
INSTALLED_APPS = [
...,
'django.contrib.staticfiles',
]
STATIC_URL = '/public/'
STATIC_ROOT = os.path.join(BASE_DIR, "public")
URLS:
urlpatterns = [
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Error I get:
Invalid block tag on ...: 'static', expected 'endblock'. Did you forget to register or load this tag?
Just use {% load static %} on the top since it is recommended in newer versions of Django. I think using staticfiles and static at the same time creates a confusion.
What fixed the issue was reinstalling Django.
I'm trying to set up my django file structure. I really don't understand this. It just isn't pointing to where I'd like it to go:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PATH = os.path.realpath(BASE_DIR)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_PATH,'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media/')
I'm trying to build a file structure like this:
mysite
myapp
static
admin
css
js
img
media
tmp
templates
base.html
manage.py
So I'd like to get the settings.py to point to the right direction, I'm just at a loss doing so.
--------- edit ----------
It's not loading any of my content in those files, except for the templates
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/main.css">
<!-- Remove line below to disable test link -->
Back To Test Page
<title>My site - {% block title %}{% endblock %}</title>
{% block head %}
{% endblock %}
</head>
<body>
<style type="text/css">
body {background-color: #ADADAD; background-image:url('{{STATIC_URL}}img/r.jpg'); background-attachment:fixed;}
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</style>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="footer">
{% block footer %}
© Copyright 2014 by Me.
{% endblock %}
</div>
</body>
</html>
The picture doesn't get loaded
You can set your project structure according to this sample project Link.and you can also use Unipath for set you dynamic path in your setting.py file. you can run this project with collect static or without collect static.