163๐
This is the working solution for static/media/template access in django for windows,
settings.py
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ('static',)
90๐
For me this turned out to be caused by setting debug to false in settings.py
. A workaround is to pass the --insecure
switch to runserver
, but the real solution is to use a proper web server to serve the static files. See the answers to this question for more details.
- [Django]-Django: Multiple forms possible when using FormView?
- [Django]-CSS styling in Django forms
- [Django]-How do I make many-to-many field optional in Django?
26๐
If you are running this on a web server are you copying the static files to a public accessible folder? For example:
# web accessible folder
STATIC_ROOT = '/home/your_name/www/mealmate/static/'
# URL prefix for static files.
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# location of your application, should not be public web accessible
'/home/your_name/website/mealmate/static',
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Then you can use this post Django static Files and copy the static files to the public accessible folder using manage.py
# --link Create a symbolic link to each file instead of copying.
# --noinput Do NOT prompt the user for input of any kind.
#
python manage.py collectstatic -link --noinput
Hope that helps!
- [Django]-Setting the selected value on a Django forms.ChoiceField
- [Django]-Select DISTINCT individual columns in django?
- [Django]-How to change the name of a Django app?
17๐
from comments above โ run this
python manage.py findstatic --verbosity 2 css/styles.css
No matching file found for โcss/styles.cssโ.
Looking in the following locations:
/Users/yourname/Documents/Workspace/test/staticfiles
I simply renamed my static folder to staticfiles and all was well. (Iโm on osx + django 1.x)
use insecure mode may not hurt if youโre on local dev box โ otherwise you may still get 404 errors.
python manage.py runserver --insecure
UPDATE
actually digging into settings.py found the infringing line.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
)
- [Django]-How to make Django serve static files with Gunicorn?
- [Django]-What's the best solution for OpenID with Django?
- [Django]-How can I serialize a queryset from an unrelated model as a nested serializer?
14๐
If you recently changed the debug to false in settings file. Follow this procedure.
Most of the time it is caused by debug setting to be false in settings.py. If you pass the โinsecure switch to runserver it should work. So if you do python manage.py runserver 0.0.0.0:8000
change it to python manage.py runserver 0.0.0.0:8000 --insecure
instead.
It should work.
- [Django]-Django Queryset with year(date) = '2010'
- [Django]-What are the limitations of Django's ORM?
- [Django]-Django optional URL parameters
9๐
I simply added the equivalent of
STATICFILES_DIRS = (
'/absolute_path_to_project/mealmate/static',
)
to get this working. Of course, replace absolute_path_to_project
with your actual path and, if necessary, add the drive letter.
- [Django]-What is choice_set in this Django app tutorial?
- [Django]-Django: Multiple forms possible when using FormView?
- [Django]-How to add url parameters to Django template url tag?
8๐
I was also stuck in the 404 problem until I realized that Apache had blocked the requests to the static dir. I used python manage.py collectstatic
to copy all the static files to the static dir under my project root, i.e. /var/my/site/static. With
Alias /static /var/my/site/static
<Directory /var/my/site/static>
Require all granted
</Directory>
in /etc/httpd/conf/httpd.conf, it works properly now.
If none of the answers above works, you may consider checking your server config.
- [Django]-How to make an auto-filled and auto-incrementing field in django admin
- [Django]-What is the difference between cached_property in Django vs. Python's functools?
- [Django]-How to test "render to template" functions in django? (TDD)
7๐
If you are suffering from this error then first check that is the debug true or false and are you using โSTATIC_ROOTโ and โSTATICFILES_DIRSโ together
For my case I have used the followings in my settings.py:
import os #(You have to import os at first)
#(If the app is in production mode then False. By default True)
DEBUG = False
#(If debug is false then add allowed hosts)
ALLOWED_HOSTS = ['*']
#(Built in)
STATIC_URL = '/static/'
STATIC_ROOT = 'static' (You have to add it to the code)
STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static') ] (You have to add it to the code)
- [Django]-Remove leading and trailing slash / in python
- [Django]-How to add superuser in Django from fixture
- [Django]-How to repeat a "block" in a django template
6๐
In my case, all I had to do was re-run the server:
python manage.py runserver
- [Django]-Python Asyncio in Django View
- [Django]-Celery discover tasks in files with other filenames
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
5๐
Iโm assuming youโre using Django1.3+ here.
First off, you need to define a few more settings:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = [
path.join(TOP_DIR, 'static'),
]
STATIC_ROOT = path.join(TOP_DIR, 'staticfiles')
STATIC_URL = '/static/'
This should help you find that directory.
Also, you should always access your static files using STATIC URL
:
<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
- [Django]-What's the purpose of Django setting โSECRET_KEYโ?
- [Django]-Python Socket.IO client for sending broadcast messages to TornadIO2 server
- [Django]-Django admin and MongoDB, possible at all?
5๐
add below in setting.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
- [Django]-New url format in Django 1.9
- [Django]-Automatic creation date for Django model form objects
- [Django]-How to use "get_or_create()" in Django?
- [Django]-Programmatically saving image to Django ImageField
- [Django]-Dynamically adding a form to a Django formset
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
4๐
in Django, you have one more option for your templates and it is linking statics like this.
this might solve your problem!
<script src="{% static 'myapp/bootstrap.min.js' %}"></script>
<link href="{% static 'myapp/bootstrap.css' %}" rel="stylesheet" type="text/css"/>
its better and easier to use
{% static โfilenameโ %}
for more information refer to , i refer you to https://docs.djangoproject.com/en/1.11/intro/tutorial06/
- [Django]-What's the difference between `from django.conf import settings` and `import settings` in a Django project
- [Django]-How to change site title, site header and index title in Django Admin?
- [Django]-Django Template Language: Using a for loop with else
3๐
in my case my static files are in resources/static
directory and I set some settings like blow in settings.py
file :
STATICFILES_DIRS = (
os.path.join(BASE_DIR, './resources/static/'),
)
and using it in my template like this:
% load static %}
<link rel="stylesheet" type="text/css" href="{% static '/plugins/bootstrap/css/bootstrap.css' %}">
this way worked for me.
- [Django]-How to tell if a task has already been queued in django-celery?
- [Django]-Django select_for_update cannot be used outside of a transaction
- [Django]-Choose test database?
2๐
change DEBUG variable to True in your settings.
the runserver method only looks for statics if debug is enabled, if not, it will look in the STATIC_ROOT url
- [Django]-Table thumbnail_kvstore doesn't exist
- [Django]-How to tell if a task has already been queued in django-celery?
- [Django]-How do you log server errors on django sites
1๐
Insert the following lines into settings.py in the main folder of your project:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'))
Then, in the html file insert:
{% load static %}
Finally, within settings.py, add django.contrib.staticfiles
into INSTALLED_APPS = [...]
- [Django]-Django filter JSONField list of dicts
- [Django]-Django logging of custom management commands
- [Django]-Separating form input and model validation in Django?
- [Django]-Are there any plans to officially support Django with IIS?
- [Django]-Django: Implementing a Form within a generic DetailView
- [Django]-Add rich text format functionality to django TextField
0๐
I think you missed to put the app INSTALLED_APPS in your settings.py file, you should add โmealmateโ
INSTALLED_APPS = (
'mealmate',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
)
After that the static and command files will be visible to django. I was having trouble with commands and this is the way I fixed it.
- [Django]-How to get form fields' id in Django
- [Django]-Backwards migration with Django South
- [Django]-Django-way for building a "News Feed" / "Status update" / "Activity Stream"
0๐
on Cpanel this is good solution here
on terminal on cpanel install dj-static static3
pip install dj-static static3
then in wsgi.py replace this code py application
from dj_static import Cling
application = Cling(get_wsgi_application())
- [Django]-Split views.py in several files
- [Django]-Querying django migrations table
- [Django]-Django โ why is the request.POST object immutable?
0๐
I faced same issue. Here how I solve of accessing static file in template.
My Django project(Recognition/) file directory look like this:
/media
/1
i1.jpg
i2.jpg
....
/static
/css
/op.css
/img
/emoji.png
/Recognition
...
/settings.py
/urls.py
...
/uploader
...
/urls.py
/templates
/uploader
/create.html
...
My settings.py look like this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Recognition',
'uploader',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
My (Recognition/urls.py) look like this:
urlpatterns = [
path('admin/', admin.site.urls),
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Then I am accessing all static files and media files in template(create.html) like this:
Here is sample code
<!DOCTYPE html>
<html>
<head>
{% block extrahead %}
<link rel="stylesheet" type="text/css" href="static/css/op.css">
{% endblock %}
</head>
<style type="text/css">
.notfound .notfound-404 {
...
background-image: url('static/img/emoji.png');
...
}
<style>
<body>
<img src="{{ MEDIA_ROOT }}/media/i1.jpg" class="image_responsive" height="100px" width="100px">
</body>
OR
You can use this django command to see where django is seeing your static files. SOURCE
python manage.py collectstatic --help
- [Django]-Where to put business logic in django
- [Django]-Good ways to sort a queryset? โ Django
- [Django]-ImportError: No module named 'django.core.urlresolvers'
0๐
for me, i do nothing but run manage.py runserver myip:port. Then i shut it down and restart uwsgi, the static files load successfully. I donโt know why but it works for meโฆ
- [Django]-How do I go straight to template, in Django's urls.py?
- [Django]-Django. A good tutorial for Class Based Views
- [Django]-<Django object > is not JSON serializable
0๐
I was able to solve this same problem by changing the js filename from camel case to snake case.
- [Django]-CORS error while consuming calling REST API with React
- [Django]-Django: Get model from string?
- [Django]-Django Footer and header on each page with {% extends }
0๐
In django version 4.1.2 STATIC_ROOT
is not working instead use STATICFILES_DIRS = [ BASE_DIR / "static" ]
- [Django]-Django: Reference to an outer query may only be used in a subquery
- [Django]-Django vs. Model View Controller
- [Django]-How to disable Django's CSRF validation?
0๐
as Django docs say; adding this code simple fixed my problem.
STATICFILES_DIRS = [
BASE_DIR / "static",
]
- [Django]-Django: reverse accessors for foreign keys clashing
- [Django]-Are Django SECRET_KEY's per instance or per app?
- [Django]-What's the best way to extend the User model in Django?
0๐
I use the standard gitignore file found here for every project. It excludes various folder names. One of the libraries I was using just happen to name the folder after one in the gitignore file. Took me a while to figure that one out!
- [Django]-Django: Get model from string?
- [Django]-How to expire session due to inactivity in Django?
- [Django]-Multiple ModelAdmins/views for same model in Django admin
0๐
Seems like youโre loading static files the wrong way in your template. The correct way to do it is,
For Django 1.6 or earlier
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.min.css" %}">
For Django 1.7 to 2.1
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.min.css" %}">
For Django 2.2 or later
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}">
EDIT:
If you specify the URL
of your static files differently in settings, itโll work differently for different values of DEBUG
. Here are two ways. (Tested on Djago 4.1)
1. This configuration will load static files when DEBUG=True
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
2. This configuration will load static files when DEBUG=False
STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = 'static/'
NOTE: Assuming your static files are present in the static folder in your projectโs root directory. Please hard refresh the browser window while testing. (For chrome hold ctrl
while clicking refresh wheel)
- [Django]-CSV new-line character seen in unquoted field error
- [Django]-Get the list of checkbox post in django views
- [Django]-ManyRelatedManager object is not iterable
0๐
For nowadays solution please try Django package Whitenoise. It is easy to install and easy to use if you followed the instructions.
some simplified steps:
-
Collect static โ make sure static files existing before install
python manage.py collectstatic
-
Install the Whitenoise โ this step depends how you managed the packages, update proper file(e.g. Pipfile or requirements.txt) and install. Below command just a example to install the package.
pip install whitenoise
-
Update the static root in settings.py
STATIC_ROOT = BASE_DIR / "staticfiles"
-
Add the following to your
MIDDLEWARE
in settings.py โ from Whwitenoise docs, Whitenoise package should place afterdjango.middleware.security.SecurityMiddleware
`MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #add it here exactly after security middleware ... ]
-
now restart or rebuild the app to check whether it is working for you.
Please check Whitenoise docs if you running into issue about installing the Whitenoise(Whitenoise docs)
a message for using staticfiles_urlpatterns
:
this only works when DEBUG=True
in settings.py
which means you should NOT use it for production environment. see reference here
- [Django]-When saving, how can you check if a field has changed?
- [Django]-Python NameError: name 'include' is not defined
- [Django]-How to pass django rest framework response to html?
0๐
in my case that was the problem:
root dir was project_name but app dir where static folder is was my_app, so django tried to find static files in project_name/static, when it was in
project_name/my_app/static, so I updated STATICFILES_DIRS = (โmy_app/static/โ,)
i also added after defining STATICFILES_DIRS in settings.py:
print('static paths are:')
for p in STATICFILES_DIRS:
print(Path(p).resolve())
to find out which was the right place, so i could get this command output when run this command:
python manage.py findstatic --verbosity 3 css/main.css
- [Django]-Django limit_choices_to for multiple fields with "or" condition
- [Django]-Add additional options to Django form select widget
- [Django]-Django override save for model only in some cases?