How to setup static files in Django [duplicate] - django

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to organize and load CSS within Django project/app?
I have follow several websites about how to setup static files in Django. Here are my steps.
Configure the setting.py:
STATIC_ROOT = '/Users/kin/mysite/static'
STATIC_URL = '/static/'
Run the collectstatic command:
python manage.py collectstatic
After that, I saw my image file is copied to the STATIC_ROOT.
Then in my template, I try to use my image file by:
<img border="0" src="{{ STATIC_URL }}images.jpg" width="304" height="228">
But there is no image when I load it on the browser. I checked the page source and STATIC_URL seems empty.
Can anyone shed some light here?
Thanks

Dont hard code the path in your setting. I usually put my static files in my main project, so my setting file look like this
import os
MAIN_PROJECT = os.path.dirname(__file__)
then
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
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.
os.path.join(MAIN_PROJECT, 'static/'),
)
After that, you can use {{ STATIC_URL }} in your view

Actually I got it right by just using the following code:
{% load staticfiles %}
<img border="0" src="{% static 'image.jpg' %}" width="304" height="228">
This will render the STATIC_URL path to me.
Thanks all for helping me out!

If you're running your app with python manage.py runserver then you may need to add the following to the end of your url conf (see docs).
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
The process for serving static files with django's dev server is different to the process for doing it with a production web server.

you can try with this
import settings in urls.py
and paste the below code in your urls.py
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'^static_media/(?P<path>.*)$',
'serve', {
'document_root': 'path/to/your/static/folder',
'show_indexes': True }),)
now go to your settings.py and change the setting like
MEDIA_URL = '/static_media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
now access your static file like
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/header.css" />

Related

Django. not able to access staticfiles in local development

I am trying serve static files in my local development (on same server I serve my site). I have run ./manage.py collectstatic with the following configs:
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
template.html
{% load static %}
<img src="{% static 'apis/icons/random-svgrepo-com.svg' %}" style="width: 50px;">
Now I have staticfiles folder in my BASE_DIR folder, but when I try to get an image, it doesn't appear to be working expected.
http://127.0.0.1:8000/static/apis/icons/random-svgrepo-com.svg
Please help. What I am doing wrong?
First of all I think you have not configured your static files and media files. Try configuring it as follows. In your settings.py ensure to include STATICFILES_DIR, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT in your settings.py and then add the below lines below STATIC_URL = 'static/':
STATIC_URL = 'static/'
MEDIA_URL = 'media/'
STATICFILES_DIRS = [BASE_DIR / 'staticfiles']
STATIC_ROOT = BASE_DIR / 'staticfiles/'
MEDIA_ROOT = BASE_DIR / 'static/media'
By doing this you are telling django where to get your static files. now your have to add the link of the static files in your project urls.py. you will add that as below.
from django.conf import settings
from django.conf.urls.static import
static
urlpatterns = [
.......
]
urlpatterns +=static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
One last thing that I assumed you had done is creating static folder in your project root and inside that static folder create media folder where all the images you want to load are. Now run python manage.py collectstatic

I have main_project/templates directory to store base.html, but where do I store base.css?

So, as I said I have a base.html file located at main_project/templates/base.html, but where do I put the base.css file? Do I create a main_project/static directory or should I just put in main_project/templates?
This seems like it should have a simple answer but I have only seen questions asking where to store base.html, and am unsure where to store base.css Thanks in advance for any responses.
All static resources go in static folder examples are, CSS,js,logo images,
STATIC_URL = '/static/'
STATIC_ROOT = ''
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
You need to add above code to settings.py to configure static directory. Then you can create a folder called 'static' where your manage.py files are.
After that in urls.py you have this
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)
And then you can use those files in the template using
<img src="{% static "my_app/example.jpg" %}" alt="My image">
Note:- if have dynamic files that change for each page, example blog post images, they are stored in media folder. To know more you can read
Read Full documentation here
https://docs.djangoproject.com/en/3.0/howto/static-files/

404 Error for django serving static files. How to setup django to serve static files?

Settings.py file in Project directory :
I already added following :
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
-> in template
<script src="{% static "validateurl/home.js" %}"></script>
I have a directory static under project directory. home.js is under validateurl directory under static.
Referring JS File using following in template html file :
Please advise what am I missing here.
Errors below :
Here are the steps to configure your django app to serve static files for local development.
The STATIC_ROOT default is None so you have to specify that in settings. Make sure you have something like this in your settings.py This tells your webserver where to find and serve the static file mapped to a url.
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Second also specify your STATIC_URL variable as it also defaults to none. following should suffice. This will be used for setting up the urlpattern.
STATIC_URL = '/static/'
You need to have a url pattern so your server knows what url corresponds to the static files
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Specify STATICFILES_DIRS variable in settings. So that the collect static manager knows where to find statics and put them in the STATIC_ROOT. This can be an array or tuple of items to different directories. This can be empty if you have no additional directories
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'pathtohomejsdirectory/'),)
Finally, make sure you run python manage.py collectstatic
This copies all the files specified in STATICFILES_DIRS over to the /static/ (STATIC_ROOT) directory to be served by django.
On a production, you want your webserver/reverse proxy say nginx or apache to serve the files. See here django documentation here

Renamed folder in Django project but old name persists

After reading more about common Django project structure, I renamed my 'media' folder to 'static' since it contains the CSS, javascript, and images for my web app and no user uploaded files. However, my project isn't finding the new directory, and the favicon is still being served and can be downloaded from the old directory at localhost:8000/media/images/favicon.png!
In my template, I am linking directly to css/js files like so:
<link href="/static/css/map.css" type="text/css" rel="stylesheet" />
There's also nothing interesting going on in urls.py:
urlpatterns = patterns('',
url(r'^$', 'EventMapperApp.views.map', name='map'),
# AJAX
url(r'^all_events/', 'EventMapperApp.views.all_events'),
url(r'^user_created_events/', 'EventMapperApp.views.user_created_events'),
url(r'^all_user_events/', 'EventMapperApp.views.all_user_events'),
# event actions
url(r'^save_event/', 'EventMapperApp.views.save_event'),
url(r'^unsave_event/', 'EventMapperApp.views.unsave_event'),
)
Any ideas?
EDIT
For some reason, I thought that urls.py didn't have to resolve all URLs for my Django app? Not really sure what I was thinking... Anyway, I've made what I thought were the appropriate changes to my code as per the documentation, but I'm still having some trouble getting it working.
settings.py
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = (os.path.join(PROJECT_PATH, "media"))
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = (os.path.join(PROJECT_PATH, "static"))
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
urls.py
urlpatterns = patterns('',
# Examples:
url(r'^$', 'EventMapperApp.views.map', name='map'),
# Required to make static serving work
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
# AJAX
url(r'^all_events/', 'EventMapperApp.views.all_events'),
url(r'^user_created_events/', 'EventMapperApp.views.user_created_events'),
url(r'^all_user_events/', 'EventMapperApp.views.all_user_events'),
# event actions
url(r'^save_event/', 'EventMapperApp.views.save_event'),
url(r'^unsave_event/', 'EventMapperApp.views.unsave_event'),
)
template
<link rel="icon"
type="image/png"
href="{{ STATIC_URL }}images/WWWfavicon.png" />
<link href="{{ STATIC_URL }}css/map.css" type="text/css" rel="stylesheet" />
<link href="{{ STATIC_URL }}css/ui-lightness/jquery-ui-1.8.21.custom.css" type="text/css" rel="stylesheet" />
<link href="{{ STATIC_URL }}css/timepicker.css" type="text/css" rel="stylesheet" />
I'm not sure what I'm doing wrong now... STATIC_ROOT seems to be resolving properly when I walk through the code (the 'static' folder is in the same directory as settings.py).
EDIT 2
As per https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development, I changed urls.py to the following:
from django.conf.urls import patterns, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
# Examples:
url(r'^$', 'EventMapperApp.views.map', name='map'),
# AJAX
url(r'^all_events/', 'EventMapperApp.views.all_events'),
url(r'^user_created_events/', 'EventMapperApp.views.user_created_events'),
url(r'^all_user_events/', 'EventMapperApp.views.all_user_events'),
# event actions
url(r'^save_event/', 'EventMapperApp.views.save_event'),
url(r'^unsave_event/', 'EventMapperApp.views.unsave_event'),
)
# only in development
urlpatterns += staticfiles_urlpatterns()
Still no luck.
See here:
Static files in templates &
Serving static files in development

how to enable /static/css URL enable in django

When I use MEDIA_URL or STATIC_URL to point to /static/ currently set MEDIA_URL to /static/
and using it in a path to CSS file like:
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/css.css" />
It points to /static/css.css, but trying http://localhost/static/css.css gives 404 error.
I have in settings:
.....
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'D:/programming/django_projects/ecomstore/'
.....
In urls.py I have point to static like this:
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root':'D:/programming/django_projects/ecomstore/'}
So where problem is? Why it is showing 404, do I need to create some view for static files? Or is there some thing else wrong in my settings or urls.py ? Any response will be appreciated, as I am newbie in django.
thanks in advance
You need to re-read the docs more closely: https://docs.djangoproject.com/en/dev/howto/static-files/
Here's some things to note:
MEDIA_URL and MEDIA_ROOT are for user uploads (FileFields and ImageFields on your models). It should be its own folder; "media" is common.
STATIC_URL and STATIC_ROOT are for your static resources. It should also be its own folder; "static" is common.
Do not actually put anything in STATIC_ROOT. This directory is only for the output of the collectstatic management command in production.
Your static resources should go in your apps' "static" folder or a completely new and different directory (i.e. not MEDIA_ROOT or STATIC_ROOT). You then add the path to that directory to STATICFILES_DIRS.
Don't add anything to urls.py. In development, Django will automatically serve anything in your apps "static" directories or any directory in STATICFILES_DIRS. In production, your webserver will be responsible for serving these files.