Django servering static files not working with dev server - python

Not sure what I'm doing wrong, but I can't get this to work. I'm using Django 1.3 and Python 2.7.
My project structure looks like this:
project
static
templates
settings.py
apps
...
In my settings.py file I have
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, 'static'))
STATIC_URL = '/static'
my urls.py file:
from django.conf.urls.defaults import *
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^grappelli/', include('grappelli.urls')),
)
urlpatterns += staticfiles_urlpatterns()
In my templates, I'm using {{ STATIC_URL }} which creates the correct path to my files, like this: /static/js/libs/modernizr-2.0.6.min.js.
None of my static files load and I've double checked the directory structure is correct. I feel like I'm taking crazy pills, so any advice is appreciated. Thanks

You should add the complete path to the dir where you place your static files in STATICFILES_DIRS in settings.py, like this:
STATICFILES_DIRS = (
'/path/to/static',
)

Either add STATICFILES_DIRS as in previous answer or put the package directory that has 'static' dir in your INSTALLED_APPS because django will automatically serve any static dir in apps during development. If your project directory is not on python path and you're not planning to make it importable then you have to define STATICFILES_DIRS and put absolute path to the static directory.

Related

Django 2.2 Not Serving Static Files

I am currently working through some tutorials to enhance my knowledge of Django. In doing so, I decided to use to most recent version of Django. I have been able to overcome most of the divergences between my code and that of the tutorial except for one - static files are not being served. Now, I am not fully sure that the difference is strictly due to the Django version. Here is what is going on.
I have the following project structure:
settings.py
STATIC_URL = '/static/'
STATIC_FILES = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'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',
],
},
},
]
What is interesting is that with this configuration, the project is able to find templates successfully. However, as mentioned above, it cannot find the static files. Why is that?
Also, this tutorial sets up an unusual configuration in that the static and templates directories are located inside the main app's directory, whereas I typically have them one level higher, i.e., in the project root's directory. Could this be a part of the problem? What in the settings of this particular project makes Django look for files one directory lower? The settings seem the same as those of other project I had done. However, those project contained the static and templates directories in the project's root directory.
Any help and clarification is appreciated.
Edit:
urls.py
from django.contrib import admin
from django.urls import path
from .views import home
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
try replacing this:
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static")
with
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "static")
Also provide the status of files (like 404 messages)
STATIC_FILES doesn't mean anything to Django, as far as I know, although maybe you are using it for another purpose.
The way you had STATIC_ROOT defined it was pointing to a non-existent directory.
There is a good reference in StackOverflow here
To serve static files you need to add the following configuration in urls.py as:
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)
Next, I believe it is a good practice to put static and templates within their own apps, this is useful if you want to make that app plug-able any near future.
Or it is also a good practice to gather all static files in project level directory and add the following in settings to identify it.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
edit: I just see the updated question. Try adding this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This says, as long as we are in debug mode serve the static files.
try this:
STATIC_ROOT = os.path.join (BASE_DIR, "taskbuster", "static")
I was able to solve the issue by changing the settings to the following:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "static")
Furthermore, it was helpful to read the following documentation when trying to understand how to fix it
https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-STATICFILES_FINDERS
Particularly, this explained clearly what Django did:
The default will find files stored in the STATICFILES_DIRS setting
(using django.contrib.staticfiles.finders.FileSystemFinder) and in a
static subdirectory of each app (using
django.contrib.staticfiles.finders.AppDirectoriesFinder). If multiple
files with the same name are present, the first file that is found
will be used.

django static url with mezzanine and templates

I've been stuck for awhile and I can't seem to get it. Before you say python manage.py collectstatic yes, I've done that.
Here's the issue: I am using one of mezzanine's solid layout. It doesn't seem like the mezzanine's files merge with the solid template layout.
On my front page, the CSS works, but if i head over to /admin page, then the css loads like this admin/static/mezzanine/some_css.css. Anything but the root main page loads the css file. So I'm guessing it's that path, but I've double checked my root path, it seems correct?
settings.py
PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH)
# PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) also tried this
STATIC_URL ='static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
# STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "solid/static"), ) also tried this
STATICFILES_DIRS = (
os.path.join(os.path.realpath(PROJECT_ROOT), "solid/static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
urls.py
urlpatterns +=[]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
simplfied file structure
app
---app
---solid
static
admin
css
mezzanine
templates
---static
admin
css
mezzanine
manage.py
You are missing an important thing named a slash in the begining. Put a slash in front.
STATIC_URL ='/static/'

Django admin: image saved but error occured when click

I am ashamed to ask a question of that sort but I still can not solve my problem. I normally uploaded image in my media directory and can see image link in my admin but if I click on link I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/photo/img/9.jpg
Using the URLconf defined in TeamStudy.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, photo/img/9.jpg, didn't match any of these.
my project structure:
src
static/
photo/
img/
settings:
PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'photo')
MEDIA_URL = '/photo/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATIC_URL = '/static/'
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
I suspect it perhaps quite simple and I miss something. Please point me.
You need to add the media MEDIA_ROOT and MEDIA_URL in your urlpatterns
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
check following links for more details
Accessing "Media" files in Django
Django classifies user files in two types
Static files
Media files
this link helps you understand the difference between them
Your issues deals with Media files.
In future development, you may need to serve static files, to serve them you will need to add
STATIC_ROOT and STATIC_URL to the urlpatterns in a similar way that MEDIA_ROOT and MEDIA_URL are added
Change your URL's patterns:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
for more info Django Docs
First point: don't put uploaded medias in you static directory - static is for static files that are part of your project (css, js etc) -, you want to use MEDIA_ROOT and MEDIA_URL for this.
wrt/ serving the static and media contents, it depends on the environment. On your local dev environment you want to use the staticfile.views to serve both static and medias as mentionned in the other answers, but don't do this in production : on a production server, you want to use your front web server to serve static (and media) contents.

django how to use template for the site's home page

Here's my folder structure (all blacked out is just name of project, just assume 'myproject'):
I want to set my home page, ie http://mydomain.com/, as a template HTML. So following this SO post, I set this as my url.py in my myproject project folder:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
url(r'^events/', include('events.urls', namespace='events')),
url(r'^admin/', include(admin.site.urls)),
)
But Django keeps trying to append this path to the events folder. The DEBUG = True output from the browser indicates that it cannot find this template at
/home/ubuntu/django/myproject/events/templates/templates/myproject/index.html
which of course is not what I was trying to point to. How do I fix this?
Django will try to find index.html template at various folders that you have specified in TEMPLATE_DIRS settings and in templates folder in each app if TEMPLATE_LOADERS setting have 'django.template.loaders.app_directories.Loader'
More details information at Loading Templates
The simplest solution is to make single templates directory on the same level as your apps.
For example:
/home/ubuntu/django/myproject/templates/events
/home/ubuntu/django/myproject/templates/some_other_app
Also, check TEMPLATE_DIRS in your settings file, here is working example:
from os.path import abspath, basename, dirname, join, normpath
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
SITE_ROOT = dirname(DJANGO_ROOT)
TEMPLATE_DIRS = (
normpath(join(SITE_ROOT, 'templates')),
)
You need to define the TEMPLATE_DIRS and try to use absolute paths like this:
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
)
...
If you have some application and your template's folder located as another folder, then you can define the TEMPLATE_DIRS in this manner:
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'events', 'templates'),
os.path.join(PROJECT_PATH, 'templates'),
)
...
And don't forget to change your views to render the template, something like this:
...
return render_to_response('events/index.html',{},context_instance=RequestContext(request))
...
EDIT:
And change your project's urls something like this:
from events import urls
...
urlpatterns = patterns('',
...
url(r'^events/', include('events.urls', namespace='events')),
...
)

How do I display an image on my webpage in Django?

I want to display an image on my website. I've been looking through the Django documentation and the other posts on stackoverflow, but I haven't gotten this to work.
I have an image name 'under-construction.jpg'. It lives in the /home/di/mysite/myapp/static/images directory.
I have a template like this:
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
in my views.py I have this:
def under_construction(request):
return render(request, 'under_construction.html')
In my settings.py, I have this:
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
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.
'/home/di/mysite/myapp/static',
'/home/di/mysite/myapp/static/images',
)
I executed ./manage.py collectstatic and it put a lot of files in /home/di/mysite/admin and /home/di/mysite/images. What do I have to do get my image to show up?
All you need to do is edit settings.py to be as the 4 following points and create a new folder (static) in the same folder settings.py is located
in the folder static you can create another folder (images) in it you can put the (under_constructioon.jpg)
STATICFILES_DIRS = (os.path.join( os.path.dirname( __file__ ), 'static' ),)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',)
STATIC_URL = '/static/'
STATIC_ROOT = ''
after you're done with the prev. points you can write
<img src="{{ STATIC_URL }}images/under_construction.jpg" alt="Hi!" />
I have faced same problem displaying the static image. suffered a lot and spent a lot lot of time in this regard. So thought to share my settings.
settings.py
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
import os.path
STATICFILES_DIRS = (
"D:/temp/workspace/offeronline/media",
(os.path.join( os.path.dirname( __file__ ), 'static' )),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ... and at the end of the file add the following line
urlpatterns += staticfiles_urlpatterns()
and finally added the following code to the template tag and it worked
<img src="{{ STATIC_URL }}images/i1.png" />
I have solved that problem like this.
STATIC_ROOT = '/path/to/project/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
Django will not directly get files directly even you do this. You need to link this static directory for each application of yours. Just go to the django app dir run following command..
cd /path/to/project/my_proj/my_app
ln -s /path/to/project/static/
This will work only in debug mod. You need to set DEBUG = true in settings.py file. This should work with django's development server.
Django won't serve any static file in production mod. You need to serve static files with web-server in production mod.
More information can be found here..
Django does support static files during development, You can use the django.views.static.serve() method in view to serve media files.
But using this method is inefficient and insecure for production setting.
for Production setting in Apache
https://docs.djangoproject.com/en/1.2/howto/deployment/modpython/#serving-media-files
set STATIC_ROOT = /path/to/copy/files/to
have you added
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve'),
or you can also do this
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
and of course try not to server static files through django it does have some overhead instead configure your http server to serve them, assuming you have an http server (nginx is quite good).

Categories

Resources