serving static files django development - django

I know a million people have asked this, and I've read and read but still cannot get this to work (I think that says something about the documentation cough cough).
ONE. CSS:
Here are my settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'))
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
also relevant:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'blog',
)
My templates are serving up just fine, while my css is not. its located in static/originaltheme.css
I've tried both:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}originaltheme.css">
and
<link rel="stylesheet" type="text/css" href="/static/originaltheme.css">
TWO. Also, is there a way to get hardcoded urls to display? for example, lets say the content of a blog post has a hardcoded url to /static/img1.jpg, how can I do that? All of the documention points to {{ static_url }}, but im guessing that that wont get evaluated when returned from a text field of a database...
is there something to do with my urls?
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'nickswebsite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
)
EDIT:
I tried doing this is in the urls:
urlpatterns = patterns('',
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=setting.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
but im getting a "settings" undefined error. I tried to import settings and im still getting an error.
Edit
Okay, the documentation for serving static off development server is HORRIBLE. Whoever wrote it should really rewrite it. This guy is the only person in the entire world who seems to explain this clearly: http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee
You DO need these in the settings.py (why arent they included in the initial installaion??? what genius...):
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
You do NOT need these:
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
You do NOT need:
manage.py collectstatic
http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee:
Points to be noted
We did not make any changes to any of the static settings provided by Django to us. We left the static settings as they were in default settings.py provided by Django.
You don't need any change in your urls.py for serving your static files in development. You don't need to add staticfiles_urlpatterns(). Many a times, I got confused with this.
You do not need python manage.py collectstatic for serving static files in development.

I also fought against this particular problem. And finally came up with this blog post
Actually you don't need collectstatic , STATICFILES_FINDER and django.contrib.staticfiles. They are all related. Read the blog post

I added these lines to the bottom of my url.py:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
And this in my settings.py:
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

Did you use:
./manage.py collectstatic
Also your STATIC_ROOT should be absolute path to the directory static files should be collected to:
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, "static"))

This is what I did for Django 2.0 using the above answers. So you'll want a system that makes deployment easy.
settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Serve Static in Development
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = [os.path.join(BASE_DIR, "appName/static/appName")]
# Serve static in production
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then made a directory ~/documentRoot/appName/static/appName/ and copied my png into it. Then in my template:
<head>
<bootstrap,jquery,etc...>
{% load staticfiles %}
</head>
<body>
<img class="mb-4" src="{% static "myImage.png" %}" alt="" width="72" height="72">
</body>
Then when you want to deploy you just run collectstatic and they'll be served in one spot. Each time you add an app, add to that list of static dirs.

Related

Django is not serving staticfiles

I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally.
This is what I have done so far:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'content.apps.ContentConfig',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path.
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
import content.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', content.views.index, name='index'),
path('/about', content.views.about, name='about'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
templates:
{% load static %}
...
{% static "css/master.css" %}
resolves to
/static/css/master.css
[EDIT]
URL PATTERN looks like this
Using the URLconf defined in website.urls, Django tried these URL
patterns, in this order:
admin/
[name='index']
/about [name='about']
^static/(?P<path>.*)$
Opening a file directly ends up to a 404-django-page.
After that, I ran ./manage.py collectstatic successfully.
I am using the Django Dev server e.g. ./manage.py runserver...
I am maybe missing something, just need an additional pair of eyes. Thanks.
Solved it by removing
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and replacing it with
STATICFILES_DIRS = (os.path.join(BASE_DIR, "staticfiles"),)

Django Will Not Pull CSS Static File (404 Error) Even Though File Paths Look Correct

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/'

How to manage media files on Windows?

I want to get media files for Django when developing application. But they just don't set up. This is my settings:
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR
STATICFILES_DIRS = (
STATIC_ROOT + '\\projectpackage\\static\\',
)
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR + '\\projectpackage\\media\\'
Templatetag:
<img class="img-responsive" src="{{ project.image.url }}" alt="">
Urls:
urlpatterns = [
url(r'^profile/', include(profile.urls)),
url(r'', include(authentication.urls)),
url(r'^project/', include(project.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^', 'views.index', name='index'),
url(r'^markdown/', include('django_bootstrap_markdown.urls')),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)
urlpatterns += static(MEDIA_URL, document_root=MEDIA_ROOT)
I can't see my mistake, because I've tried every other advices in other questions. And everything works bizzare. Static files are running good, media uploading to media/prj_img, but when I try to show image at template I've got such strange result:
<img class="img-responsive" src="/media/C%3A/Development/projectdirectory/projectpackage/media/prj_img/wallhaven-131_od9FWLX.jpg" alt="">
How could I fix this media error? This is strange, because everything looks right. Why there are full path in url?
Edit:
BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Also I've figured out that I've got wrong upload_to and changed it to prj_img. Now I've got following link:
<img class="img-responsive" src="/media/prj_img/wallhaven-24700.jpg" alt="">
But still it's not displating.
I have a lot of comments on your code.
STATIC_ROOT location is not appropriate. With your settings collectstatic command will put everything in your project's directory. Change it like so:
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
But take care, that this folder is accessable (both permissions and django-settings) in production.
Use os.path.join to join folders:
STATICFILES_DIRS = (
os.path.join(STATIC_ROOT, 'projectpackage', 'static')
)
This url pattern must be the last one and contain $:
url(r'^$', views.index, name='index'), # do not pass strings
These two url patterns do the same (docs):
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)
Moreover, you do not need them. Just ensure, that INSTALLED_APPS setting contains 'django.contrib.staticfiles'.

Django 1.4 serving MEDIA_URL and STATIC_URL files on development server

Just upgraded to Django 1.4, and having serious trouble with the new 'improved' serving of static and media files on development server. I love Django, but why on earth they have made serving these files doubly more complicated with STATIC_URL,STATIC_ROOT, STATICFILES_DIR now is utterly beyond me.
I'm simply trying to serve all files, static and uploaded, on the development server. I have the STATIC_URL files working, after much experimentation, but I simply cannot get the MEDIA_URL files to be served as well.
Settings:
DIRNAME = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(DIRNAME, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
I've got the media and static context processors added:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
'django.core.context_processors.media',
'django.core.context_processors.static',
"django.core.context_processors.request",
'satchmo_store.shop.context_processors.settings',
'django.contrib.messages.context_processors.messages',
)
and I've added in the url confs:
# serve static and uploaded files in DEV
urlpatterns += staticfiles_urlpatterns()
urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
with the two conf settings added as indicated in the docs, first one for static, second for media.
my structure, website being an app and static dir placed inside it as instructed on djangoproject:
<myproject>
--media
--settings
--templates
--website
|->static
In templates I can serve static content no problem with
{{STATIC_URL}}css/style.css
But any uploaded image, this one using photologue, is not served, but the urls are correct:
/media/photologue/photos/cache/spawning-2_admin_thumbnail.jpg
That directory structure does exit under media/
Super, super confused. It all seems so ridiculously complicated now, whereas I never had any issues before.
I´m very new to Django and I´ve never had any problem with static content.
This is my configuration. I hope it can help
My folder structure
django-project
--mainapp
----settings.py
----wsgi.py
----[...]
--otherapp
--fixtures
--static
--templates
--manage.py
--requirements.txt
settings.py
import os, socket
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MAIN_APP = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(MAIN_APP, ".."))
MY_LOCALHOST = "VirusVault.local" # this is the real name of my local machine :)
try: HOST_NAME = socket.gethostname()
except: HOST_NAME = "localhost"
[...]
if HOST_NAME == MY_LOCALHOST:
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATIC_URL = "/static/"
MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media/')
MEDIA_URL = "/media/"
else:
STATIC_ROOT = "/server/path/to/static/files"
STATIC_URL = "http://server.com/static/"
MEDIA_ROOT = "/server/path/to/static/files/media/"
MEDIA_URL = 'http://server.com/static/media/'
You need to add 'django.contrib.staticfiles' to INSTALLED_APPS
urls.py
if settings.HOST_NAME == settings.MY_LOCALHOST:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
)
If you are using Django 1.4 folder structure, you've moved settings.py to your new website app folder which means your MEDIA_ROOT is now incorrect. Not sure if a relative location works in this case, but it should be something like this
MEDIA_ROOT = os.path.join(DIRNAME, '../media/')
It might be simpler to use an absolute path.
I intended to write a comment first but somehow add comment button doesn't work.
Did you check the permissions of media directory?
Since it became an answer, I am going to dump one of my perfectly working Django 1.4 sites configuration.
structure:
-myproject
-- media
-- static
-- templates
-- myproject
--- settings.py
--- urls.py
settings.py:
PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) # Not the best way but works
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATIC_URL = '/static/'
urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
...
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()

appfog django static files

I've a project, actually is the test from appfog (https://github.com/appfog/af-python-django) that run smoothly in localhost. But it does not work, at least static files are not recognized once deployed on appfog.
I've changed just the location of tempaltes.
This is the test page http://st-test.eu01.aws.af.cm/ . as well, also the admin pages are without css http://st-test.eu01.aws.af.cm/admin/
this is my configuration (setting.py)
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
i also tried with
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static')
but nothing changes.
i've tried with doing collectstatic locally and then update the files on the repository, but nothing works.
does anyone of you know how to make it working?
btw, in the template i use {% load staticfiles %} and {% static "css/style.css" %}
This works for me:
settings.py:
import os
ROOT_PATH = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(ROOT_PATH, 'static')
STATIC_URL = '/static/'
urls.py:
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),