Correct path/url for media files in django - python

I am using django 1.5.2 and I am having a hard time understanding the purpose of the media directory vs. the static directory and how to include stylesheets in my django project.
This is my directory structure:
django_books
beer
__init__.py
admin.py
models.py
views.py
random_book
(same as beer above)
django_books (the actual django project; beer and random_book above are my apps)
templates
base.html
beersall.html
__init__.py
settings.py
urls.py
views.py
wsgi.py
static
css
beers.css
media
css
beers.css
static
css
beers.css
manage.py
My beersall.html template (the beer output is correct, so just linking the stylesheet is wrong):
{% extends 'base.html' %}
{% block content %}
<div id="beer_list">
{% for beer in beers %}
{{ beer }},
{% endfor %}
</div>
{% endblock %}
My base.html file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="/media/css/beers.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/beers.css" />
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/beers.css" />
<link rel="stylesheet" type="text/css" href="/static/css/beers.css" />
<link rel="stylesheet" type="text/css" href="/Users/username/Projects/django_books/media/beers.css" />
<link rel="stylesheet" type="text/css" href="/Users/username/Projects/django_books/static/beers.css" />
<link rel="stylesheet" type="text/css" href="/Users/username/Projects/django_books/django_books/static/beers.css" />
{% block extrahead %}{% endblock %}
</head>
<body>
<div id="page_container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
My settings.py file:
MEDIA_ROOT = '/Users/username/Projects/django_books/media/'
MEDIA_URL = '/Users/username/Projects/django_books/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
I should note that I am using the django development server, not apache.
The error in my browser (developer console) says beers.css is 404.
The url is localhost:8000/beers/ and my urls.py file correctly points to this and the views.py correctly serves the beersall.html template. How can I properly link my media?
EDIT
When I change the css link href value to /Users/username/Projects/django_books/media/ it still doesn't work.
EDIT 2
I've updated the href values to show things I've tried. Still not working...

User-uploaded files (by admins or site users) go to media directory.
Static files are files provided by developers (or from third-party apps).
Set something like this:
# Local disk paths
MEDIA_ROOT = '/Users/username/Projects/django_books/media/'
STATIC_ROOT = '/Users/username/Projects/django_books/static/'
# URLs visible in the browser's address bar
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
And in Your template use the STATIC_URL variable:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/beers.css" />
And move your styles to the django_books/static/ directory.

in my project:django_learn, in template: check_uncheck_all.html, part pf the code:
{% load staticfiles %}
<html>
<head>
<script type=text/javascript src="{% static 'js/jquery-1.9.1.js' %}"></script>
</head>
you can also have a look at my settings.py

The static files were being found, but the permissions were not set up correctly. (i.e. a 403 not a 404 server error)
<VirtualHost *:80>
WSGIScriptAlias / /Users/username/Projects/django_books/django_books/django.wsgi
#the directory tag before was /Users/username/Projects/django_books/django_books/>
#this was one directory too deep
#from my structure above, you can see I needed to change my directory tag to this:
<Directory /Users/username/Projects/django_books/>
Order Allow,Deny
Allow from All
</Directory>
<Directory /Users/username/.virtualenvs/django_books/lib/python2.7/site-packages/django/contrib/admin/static/admin/>
Order Allow,Deny
Allow from All
</Directory>
Alias /static/admin/ /Users/username/.virtualenvs/django_books/lib/python2.7/site-packages/d$
Alias /static/ /Users/username/Projects/django_books/static/
</VirtualHost>

Related

Parent directory symbol not working in html

<meta charset="utf-8">
<title>Exam Page</title>
<link rel="stylesheet" href="../../../static/css/teststyle.css">
</head>
Im using this code in exam folder and i wanted to go to parent directory so i used ../../ but it is showing the below error
Not Found: /exam/static/css/teststyle.css
At the top of your template add {% load static %} and to add your css you can use {% static 'css/teststyle.css' %}.
{% load static %}
<meta charset="utf-8">
<title>Exam Page</title>
<link rel="stylesheet" href="{% static 'css/teststyle.css' %}">
</head>
In your main urls.py add
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and in your settings.py add
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

django html template can't find static css and js files

I have a django project that structure is like this:
>vira
>vira
-__init.py
-settings.py
-urls.py
-wsgi.py
>vira_app
>migrations
>template
-index.html
>static
>vira_app
>assets
>css
>js
>vendor
>aos
>bootstrap
>bootstrap-icons
>isotope-layout
>swiper
-__init__.py
-admin.py
-apps.py
-models.py
-tests.py
-urls.py
-views.py
-db.sqlite3
-manage.py
I have used bootstrap. index.html is like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load static %}
<link href="{% static 'vira_app/assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet">
<link href="{% static 'vira_app/assets/vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet">
{% load static %}
<link href="{% static 'vira_app/assets/css/style.css' %}" rel="stylesheet">
</head>
<body>
<main id="main">
<div id="portfolio-grid" class="row no-gutter" data-aos="fade-up" data-aos-delay="200">
{% if catalogue_list %}
{% for Catalogue in catalogue_list %}
<div class="item web col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="{{ Catalogue.link }}" class="item-wrap fancybox">
<div class="work-info">
<h3>{{ Catalogue.title }}</h3>
<span>{{ Catalogue.source }}</span>
</div>
<img class="img-fluid" src="{{ Catalogue.image }}">
</a>
</div>
{% endfor %}
{% endif %}
</div>
</div>
</main>
<i class="bi bi-arrow-up-short"></i>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'vira_app', 'template')
],
'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',
],
},
},
]
STATIC_URL = '/static/'
STATIC_ROOT = '/vira_app/template'
When I run the server and go to index.html, data retrieved from db and show well, but without any style!
I have tried some solution, check every static url, but not working
In fact, css, js and vendors not applied. What's the problem?
Some of settings are misused:
STATIC_URL = '/static/' - this is fine
STATIC_ROOT = '/vira_app/template' - nope, this is supposed to be some folder not really related to the project structure. In the end, on prod it can be a CDN URL or a folder on different server. So try changing it to something like STATIC_ROOT = os.path.join(BASE_DIR, 'static') for the start.
As mentioned in comments you might need to define STATICFILES_DIRS - a list of folders where from static files must be collected to STATIC_ROOT by collectstatic command. This means you can have many subfolders containing static files in different places. However you'll need to collect those files all together to deploy somewhere. STATICFILES_DIRS + collectstatic will collect all of those files for you into given STATIC_ROOT (and contents of this folder should be deployed somewhere, to CDN for example).
Note, default set of STATICFILES_FINDERS already contains AppDirectoriesFinder which will automatically find all the static subfolders in any of the project apps. This means if you move static subfolder from templates to the vira_app root - you won't have to mention it in the STATICFILES_DIRS.
So:
STATIC_ROOT should not point to any templates subfolders, change it to something more "global"
STATICFILES_DIRS should link to the folder(s) where you keep your static files now or this folder should be moved to the root of vira_app to let collectstatic find it
collectstatic must be run before checking your styles and scripts in rendered page
after running collectstatic all the static files must persist in STATIC_ROOT so django will be able to map relative urls after STATIC_URL to relative paths after STATIC_ROOT and those files will be loaded
PS
Note, some of your static files are linked in wrong way in the shown template:
<script src="assets/vendor/aos/aos.js"></script>
this should be changed to {% static... as well.

Setting static file

The problem is setting the static file.
I set the file according to the official document said.
I first created a directory called static in the app which my URL links to
Then I made some changes on the template.
The code is below:
#Structure
src
|---makesite
|---sitemaker(app)
|---templates
| |----main.html
| |----static
| |-css
| |-style.css
|-static
|-manage.py
#The settings.py
STATIC_URL = '/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),]
STATIC_ROOT = os.path.join(BASE_DIR,"templates/static")
#The urls.py
from django.conf.urls import url
from django.contrib import admin
from makesite.views import make_site
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^main/',make_site),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, documents_root=settings.STATIC_ROOT)
#The File structure
#The template
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<title>Main Site</title>
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'>
<link rel= "{% static %}'css/style.css'" href="style.css">
there is error in your template code. You should rewrite link tag to this:
<link rel="stylesheet" href="{% static 'css/style.css' %}" type="text/css">
In the settings.py file:
STATIC_URL = '/static/'
In order to load the static files in .html just use:
{% load static %}
Its always better to use {% load static %} on the top of the file.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Website{% endblock %}</title>
and suppose you have base.html and somefile.html that extends the base.html use it like this:
{% extends "appname/base.html" %}
{% load static %}
In your code:
use:
<link href="{% static "css/style.css" %}" rel="stylesheet">
That will solve the problem.

How should my Django file structure be set up?

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.

href static files Django STATIC_URL and STATICFILES_DIRS

My settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
In my html page is href to my files using
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/default.css">
<img src="{{ STATIC_URL }}images/pythonlogo.jpeg">
I also tried:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/default.css' %}">
<img src="{% static 'images/pythonlogo.jpeg' %}">
The error I am getting in developer tools is
GET http://127.0.0.1:8000/static/css/default.css 404 (NOT FOUND)
GET http://127.0.0.1:8000/static/images/pythonlogo.jpeg 404 (NOT FOUND)
I tried to print the path on to the web page by simply placing {{STATIC_URL}} on the page and /static/ appears.
My project directory path is:
django_test/
admin/
article/ <-- app
templates/
django_test/
templates/
static/
css/
images/
STATIC_ROOT is directory where all your static files will be copied by collectstatic command.
You should specify your path to STATICFILES_DIRS tuple to use it with built in webserver.

Categories