Its my first project in django,so i dont know a lot of things.firstly, i want to serve static files from django STATIC_ROOT, not STATICFILES_DIRS.
this is my project tree:
src >>
...db.sqlite3
...manage.py
...mainapp (main module)
...__init__.py
...settings.py
...urls.py
...wsgi.py
...myapp (django app)
...Migrations(Folder)
...__init__.py
...admin.py
...apps.py
...models.py
...tests.py
...views.py
...accounts (django app)
...Migrations(Folder)
...__init__.py
...admin.py
...apps.py
...models.py
...tests.py
...views.py
...templates
...myapp
...home.html
...accounts
...
...
...static
...myapp
...css
...bootstrap.css
...home.css
...js
...images
...accounts
...
...
...
...static_cdn (STATIC_ROOT)
...admin
...
...
...
...myapp
...css
...js
...images
...accounts
...css
...js
...images
in settings.py :
INSTALLED_APPS = [
'myapp',
'accounts',
.....,
.....,
.....,
'django.contrib.staticfiles',
]
.......
.......
.......
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR,'static_cdn')
in urls.py :
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
.......
from myapp.views import (
.......,
.......,
)
from accounts.views import (
.......,
.......,
)
urlpatterns = [
.......,
.......,
.......,
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
in home.html in templates :
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
<title>.......</title>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/css/bootstrap.css'%}"/>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/css/home.css'%}"/>
</head>
<body>
.......
.......
.......
</body>
</html>
Then i run the command:
(clashsite) D:\DjangoSite\clashsite\src>python manage.py collectstatic
and following happens:
211 static files copied to 'D:\DjangoSite\clashsite\src\static_cdn'.
Now,the endpoint,what i want is : i dont want to serve my static files from 'static' folder in my tree, but from 'static_cdn' folder.more precise,i dont want to serve static files from STATICFILES_DIRS , but from STATIC_ROOT. But the content are served from only static folder.if i remove the static folder,static files are not served from static_cdn or STATIC_ROOT.How can i do that??
#ruddra has already explained to you.
to serve your static assets static_cdn in production environment you need a web server like apache or nginx but you can use xampp or wampserver to serve your Django app locally (a mimic production environment as you said) and access it like any web app
served with real domain name (e.g: http://hellodjango.local/)
install mod_wsgi for apache (https://pypi.org/project/mod-wsgi/) globally (meaning deactivate first the current virtual environment of your Django app)
you need to make some changes to wsgi.py file to include activate_this.py script.
and then create vhost conf file for your app
<VirtualHost *:80>
ServerName hellodjango.local
# the root project folder
DocumentRoot "C:/myapps/hellodjango"
WSGIScriptAlias / "C:/myapps/hellodjango/src/mainapp/wsgi.py"
<Directory "C:/myapps/hellodjango/src/mainapp">
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Alias /static_cdn "C:/myapps/hellodjango/src/static_cdn"
<Directory "C:/myapps/hellodjango/src/static_cdn">
Require all granted
</Directory>
# Alias /media_cdn "C:/myapps/hellodjango/src/media_cdn"
# <Directory "C:/myapps/hellodjango/src/media_cdn">
# Require all granted
# </Directory>
...
</VirtualHost>
and don't forget to add 127.0.0.1 hellodjango.local in windows hosts file and restart apache server.
NB: you can also configure MEDIA_URL and MEDIA_ROOT (for file uploads) the same as STATIC_URL and STATIC_ROOT.
hope this brings you the missing piece of puzzle.
Usage of STATIC_ROOT is bit different and it is related to production deployment. What you are seeing here is Django serving contents when you are in DEBUG=True mode. It is serving content through staticfiles app.
STATIC_ROOT is the directory where static files are stored when you run collect static. But serving from that directory is not what django will do. If you are in production mode(aka DEBUG=False), Django will not serve any static contents. Then you need to use a reverse proxy server like NGINX or Apache to serve those static files from STATIC_ROOT directory.
More information can be found regarding this on documentation.
Related
I am using Django and React to create a web application. When it comes to my React Development server, my favicon.ico loads like it should, but when I build my files, my Django development server doesn't find and render my favicon, and I have no idea why. I've tried renaming my favicon and changing the file type to .png. When I put my favicon into my static directory, and change the file name from favicon to some thing like "icon.ico", then it loads properly. But, I can't have my favicon in my static directory because CRA won't copy it into that directory when it builds. It's probably something small and simple so I'll show y'all all of the related files. Thanks for any insight!
EDIT: I tried collectstatic , but that did not help
EDIT 2: using {% load static %} but this doesn't work because my favicon is in the same directory as my html file. I should also clarify that import links to the parent directory that holds both my html file and my favicon file don't register for some reason.
The import in my build/index.html: <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico"/>
urls.py
from django.contrib import admin
from django.urls import include, path, re_path
from django.conf.urls import include, url
from backend import views
from django.views.generic.base import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('backend.urls')),
path(r'^api/<int:pk>$', include('backend.urls')),
path(r'^api/<int:pk>$/', include('backend.urls')),
url(r'^.*$', views.index),
]
my settings.py static settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(FRONTEND, 'build/static/'),
]
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
)
Also, let me know if the problem could be in another file
The problem is that the django url routing has no access to the favicon.ico since CRA puts it in /build and all your static files are served from /build/static.
Assuming you haven't ejected, a hacky solution is to copy the favicon.ico into the static folder in your build step in package.json scripts section:
"build": "react-scripts build && cp build/favicon.ico build/static/favicon.ico"
and then in the html template in /public, set the favicon.ico url to
<link rel="shortcut icon" href="/static/favicon.ico">
instead of %PUBLIC_URL%/favicon.ico.
If you have ejected the CRA, you can update your webpack config to move the favicon.ico directly into /build/static
I'm in the process of setting up an Apache web server on an Ubuntu VM using Django with the intention of configuring it for production. I used this walk-through to get Apache and Django up and running, and since, I've been following along with the official tutorial provided in the Django docs. I've gotten up to Part 6, which discusses managing static files, but I can't seem to get the styling to apply.
Abbreviated Server File Structure:
/etc/
--apache2/
----apache2.conf
....
/build/
--django/ <-- Django installation
--tstdj/ <-- target project
----manage.py
----polls/
------...
------static/
--------polls
----------styles.css
------templates/
----------....
----------index.html
------urls.py
------views.py
----static/
------....
------polls/
--------styles.css
----tstdj/
------....
------settings.py
------urls.py
------wsgi.py
/etc/apache2/apache2.conf:
....
WSGIDaemonProcess www-data processes=2 threads=12 python-path=/build/tstdj
WSGIProcessGroup www-data
WSGIRestrictEmbedded On
WSGILazyInitialization On
WSGIScriptAlias / /build/tstdj/tstdj/wsgi.py
Alias /static/ /build/tstdj/static
<Directory /build/tstdj/tstdj>
Require all granted
</Directory>
<Directory /build/tstdj/static>
Require all granted
</Directory>
<Directory /static>
Require all granted
</Directory>
/build/tstdj/tstdj/settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
....
STATIC_ROOT = BASE_DIR + '/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
'/build/tstdj/polls/static',
]
#STATIC_DIRS = 'static'
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
/build/tstdj/polls/templates/polls/index.html:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/styles.css' %}">
<p><span>My name Jeff</span></p>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question. question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
/build/tstdj/polls/static/polls/styles.css:
li a {
color: green;
}
Obviously, the desired output in this case is to have green links. The network tab of the inspector shows 403 errors on the styles.css file, as does attempting to go straight to localhost:8080/static/.
I've run python manage.py collectstatic and sudo service apache2 restart Lord knows how many times. I know there are means of getting the styling to work in development, but I've yet to get them functional for production.
My issue was that I attempting to change permissions in /etc/apache2/apache2.conf rather than /etc/apache2/sites-available/000-default.conf.
Apache 403 while serving Django static files
In my settings file i have the following
STATIC_URL = '/static/'
my app name is reg_service
So my directory structure is like reg_service/reg_service/settings.py
And i have the static directory in reg_service/static/js
reg_service/manage.py
reg_service/reg_service
reg_service/templates
But in my template if i include the following script the result is "GET /static/js/jquery.min.js HTTP/1.1" 404 1652 whats is wrong here
<script src="{{ STATIC_URL }}js/jquery.min.js"></script>
The idea of django is that you should serve your static files directly through your web server.
For development purposes you can 'trick' django to serve the static files themself:
urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Django will find your static files, and serve them under the url defined under STATIC_URL.
That's not very performant nor secure, but works ok for development. For production you should configure your web server (Apache, Nginx, whatever) to serve the files directly under the url defined in STATIC_URL.
For more information see: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development
I have spent all day and nothing works. I have seen at least 20 posts here about the same topic and they are different with different suggestions and nothing works for me.
Running Django 1.6 with Python 2.7.+
I'm trying to load the css for the polls app from the django tutorial.
project layout
Project
|-polls
|-static
|-polls
style.css
|static
here is the settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/static'
template code
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
urls.py
urlpatterns = patterns(...)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
polls/urls.py
urlpatterns = patterns(....,url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),)
After running: python manage.py collectstatic, everything is collected and static folder which is on root gets populated accordingly with the admin and polls folders and files.
I start the server: python manage.py runserver everything works fine except the css is not loaded
this is what i get from the Chrome console when i inspect the html
....
<link rel="stylesheet" type="text/css" href="/static/polls/style.css">
....
which looks fine but gives the following output
[16/Nov/2013 00:44:41] "GET / HTTP/1.1" 404 2141
[16/Nov/2013 00:44:45] "GET /polls/ HTTP/1.1" 200 820
[16/Nov/2013 00:44:45] "GET /static/polls/style.css HTTP/1.1" 404 1649
Any help would be appreciated. I followed everything step by step. I don't know what to do anymore
UPDATE
DEBUG=True
full urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from PoolsDjangoProject import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'PoolsDjangoProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
full polls/urls.py
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(),name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='votes'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),
)
And when i try to access
http://127.0.0.1:8000/static/polls/style.css
I get
Page not found (404)
'polls/style.css' could not be found
I found it necessary to restart the running server after following the steps in
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
in order to pick up the newly created static directory. That step isn't listed in the tutorial. I have opened a ticket requesting its addition.
I realise this answer is not likely to help your specific case but this question comes up prominently in Google when searching for problems with adding a static directory to the example Polls app.
I ran into this problem too. My problem was that I didn't have my main app in the installed apps, whatever folder that has wsgi.py in it, that needs to be in INSTALLED_APPS.
I struggled with this problem as well.
Here's how I solved it (DEBUG=True):
After creating a project and several apps, I created a directory called "static" that sat alongside my app directories (same level as .manage.py).
I set my static URL to '/static/' in settings
I set my static root to STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/')) (BASE_DIR = os.path.dirname(os.path.dirname(__file__)))
I set my staticfiles dirs to STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), '/Users/username/sites/containing_dir/project_dir/static/',) (assumes OSX path)
I added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls.py for my project
My static media is now served from http://127.0.0.1:8000/static/css/styles.css (assuming runserver command).
Comment if you need addition description!
Firstly it has to be known that Django is not responsible for serving static files on production servers. However, it does serve them when DEBUG=True during development for the sake of debugging.
For serving static files when debug=true you have to do nothing. I don't know why it is creating confusion among newbies on how to setup it. The below should help you create static files for both production and dev modes clearly
Development mode : when DEBUG=True
create your project django-admin.py startproject mysite
create your app manage.py createapp myapp
Add myapp to INSTALLED_APPS in settings.py
In myapp dir, create a folder static
In the myapp/static dir, save a file myfile.css
In settings.py, provide a valid address to STATIC_ROOT folder to store static files. It could be something like os.path.join(os.path.abspath(os.path.dirname(__file__)), "mystatic") if you want to store your collected files at mysite/mysite/mystatic.
run manage.py collectstatic; now you have to see the static file collected at the directory you mentioned above..It should also create one if its not present. You are free to put any directory.
test the url http://127.0.0.1:8000/static/myfile.css
In case if its not working yet, try restarting the site.. New files are not recognized dynamically!
How can I view my static css files? I've set my STATIC_ROOT, and am using python manage.py runserver.
In my development environment, according the docs, I only need to place my static files (in this case, /static/css/typography.css) in my STATIC_ROOT, and python manage.py runserver will automatic create the views necessary to access it if I have DEBUG = True.
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "static")
I've also tried manually adding the views in URLConf, which won't display the css file either:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
In my template, the {{ STATIC_URL }} gets to the correct address (/static/css/typography.css), but it will not serve the file when I try to access it:
<link href="{{ STATIC_URL }}css/typography.css" rel="stylesheet" type="text/css">
Notes: The other Django related static files questions on StackOverflow are over two years old. Django version 1.3b1 differentiates STATIC (static files, such as css and images) and MEDIA (user-uploaded file).
Besides. all the tries mentioned above, you must also make sure that your template is receiving the RequestContext when called from the view.
http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
This link gives various ways of doing the same and you could choose any one. :) Also, the TEMPLATE_CONTEXT_PROCESSORS must be added to settings.py for this to take effect.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"myapp.processor.foos",
)
Note: STATIC_ROOT is the place where all your static files are stored by Django after collecting them from STATICFILES_DIRS.
Runserver will pick them up from the path mentioned in STATIC_ROOT, so STATIC_URL should point to the same location as STATIC_ROOT.
Answered here: Django staticfiles app help
I was putting my files in STATIC_ROOT, so adding this works:
STATICFILES_DIRS = (STATIC_ROOT,)
In development:
#settings.py have this by default
STATIC_URL = '/static/'
This means when you want to use static files, django will look for them in folder 'static' in your app directory. So you need to create folder 'static' in every your app and put inside your static files.
In production:
1. Make place to hold static files from all app's
STATIC_ROOT = "/var/www/example.com/static/"
2. Run python manage.py collectstatic to collect static files from all app's in STATIC_ROOT folder.
3. In settings.py change DEBUG=False and ALLOWED_HOSTS = ['yourhostadress'].
4. Point your webserver to STATIC_ROOT folder (eg. for Apache2.4):
Alias /static/ /path/to/mysite.com/static/
<Directory /path/to/mysite.com/static>
Require all granted
</Directory>
After this setup, your django project should be able to run (using mod_wsgi) and use static files on Apache web server.