When working locally on a Django project that uses static files and the default static files backend, I am running into an issue when I want to get full absolute urls to the static files instead of only the path.
My settings:
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent
INSTALLED_APPS = ["django.contrib.staticfiles", ...]
STATIC_ROOT = BASE_DIR / "static_root"
STATIC_URL = "/static/"
MEDIA_ROOT = BASE_DIR / "media_root"
MEDIA_URL = "/media/"
STATICFILES_DIRS = (BASE_DIR / "static",)
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
Everything works, the admin's CSS is loaded, images work, etc. But when I get the path of a file with this code:
from django.contrib.staticfiles.storage import staticfiles_storage
static_path = staticfiles_storage.url("path_to_folder/some_file.jpg")
That result is a relative path: /static/path_to_folder/some_file.jpg. This is a problem when these urls are used from my external frontend: it now has to prepend the backend's base url to all static assets. But if I'd want to deploy the static assets to S3 for example, in production, then I should not prepend these paths with the domain of the backend.
So what I tried to do was to change the STATIC_URL setting to http://localhost:8000/static/. That way the full url is passed to the frontend, but I could really easily change this setting in the backend in production.
And this is where the problem rears its head: when I change STATIC_URL to http://localhost:8000/static/, none of my static files work anymore, I just get a 404. The admin page also is completely unstyled because of this.
So, to make a long story short: how can I use an absolute STATIC_URL in local development mode with DEBUG=True?
I have created a reproduction repro: https://github.com/kevinrenskers/django-problem-repro.
Found the solution here: https://docs.djangoproject.com/en/4.1/ref/contrib/staticfiles/#django.contrib.staticfiles.views.serve.
Simply add this to the end of urls.py:
from django.conf import settings
from django.contrib.staticfiles import views
from django.urls import re_path
if settings.DEBUG:
urlpatterns += [
re_path(r'^static/(?P<path>.*)$', views.serve),
]
Then the static files will work again even with an absolute URL as the STATIC_URL setting.
I created a project with Django as backend and Vue js as frontend. Initially I ran Django on one server(8000) and Vue js on another (8080) with node.js . Then, I integrated Both to the same server with proxy changes in vue.config.js. Then I ran the command NPM RUN BUILD on terminal and I moved the dist folder to Django's static folder to render. This worked perfectly in local development environment but I'm getting 404 error for static files while deploying the project in Azure web services through git-hub. Thanks for any fix or sugesstions.
Here is my settings.py file. I have also tried commenting STATIC_ROOT
STATIC_URL = '/static/'
# Vue assets directory (assetsDir)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here is my vue.config.js
module.exports = {
devServer: {
proxy: {
'^/api/': {
target: 'http://127.0.0.1:8000/api/',
ws: false,
}
}
},
// outputDir must be added to Django's TEMPLATE_DIRS
outputDir: './dist/',
// assetsDir must match Django's STATIC_URL
assetsDir: 'static',
publicPath: '',
baseUrl: '',
}
Here is my project file structure
Here is the error in my console
If you are running on production server, static files are served differently from dev server. Additional changes has to be made in main urls and settings. Docs link
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# your url patterns
]
# for serving static files
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# for serving media files (files that were uploaded through your project application)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Obviously, you have to add STATIC_URL, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT in project settings.py file.
Also, you need to run python manage.py collectstatic after setting STATIC_ROOT. Docs link 1 and link 2
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
My enviroment is with Django 1.10.7, PostgreSQL 9.4 and Nginx 1.6 with Gunicorn
I have a global folder called static for common static files to use in sub apps, then i set another folder for production mode with the name 'static_root':
in my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
in my urls.py:
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
urlpatterns += (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
when debug is true all work perfect, but in production mode the site not see the static files
i set the location in nginx configuration too
thank!
i found the answer to my question,
the problem was that i set in the nginx configuration: root
location /static {
root /var/projects/project/static_root;
}
the correct way is: alias
location /static {
alias /var/projects/project/static_root;
}
I'd like to love Django, but this business of static and media files in development environments is driving me nuts. Please rescue me from my stupidity.
I'm on my development machine. I have folder media in the root of my project directory.
In settings.py I have: MEDIA_ROOT = '' and MEDIA_URL = '/media/'.
In urls.py I have:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, }),
)
But the only way I can get media files is by referencing /media/media/ e.g.
<img src="/media/media/image.png" />.
I expect (and want)
<img src="/media/image.png" />
Can anyone tell me what is happening here, and give me a simple recipe for setting up media file handling?
Thank you very much.
#Timmy O'Mahony - thanks! epic post, and very clear. But it leaves a couple of questions:
(1) I have to use /media/ and /static/, not media/ and static/ as MEDIA_URL and and STATIC_URL - am I missing something?
(2) If collectstatic hoses /static/, where do you put site level CSS e.g. the site's CSS files? Not in /static/, evidently.
(3) I put them in a directory '_' off the project root and set STATICFILES_DIRS to point to it - and that seems to be where the development server gets its static files, despite the urlpatterns directive. If THAT is wrong, where do you put site level CSS during development, and what is the workflow around collectstatic when you modify them - do you have to edit them one place, and collect them someplace else after every edit?
Folder Setup:
Your project root should be something like:
/app1
/app2
/media
/static
/templates
urls.py
settings.py
manage.py
The media folder is supposed to hold things like images, downloads and other material that might be uploaded during normal use of the website (i.e. after development is finished)
The static folder is supposed to hold all the CSS/JS and other material that is a part of the development of the site
Settings.py:
MEDIA_ROOT is the absolute server path to the static folder mentioned above. That means it should be something like:
MEDIA_ROOT = "/User/Bob/Sites/MySite/Project_root/media/"
MEDIA_URL is the relative browser URL you should access your media files from when you are looking at the site. It should be (usually)
MEDIA_URL = "media/"
which means all material can be viewed at http://example.com/media/
Similarly, STATIC_ROOT should be something like
STATIC_ROOT = "/User/Bob/Sites/MySite/Project_root/static/"
and STATIC_URL be
STATIC_URL = "static/"
Serving the files:
Now that you have told django where these folders should be, and the correct URLs to access them, you need to serve all requests to the folders correctly.
Usually when you are in production, you want the webserver to take care of serving your static files and media files.
If you are developing though, you can just get the django development server to serve them for you.
To do this, you tell it to route all request that come in to http://example.com/media to your MEDIA_ROOT and all requests that come in to http://example.com/static to your STATIC_ROOT.
To do this, you add some URLS to URLS.py like you have:
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
Extra:
If you have multiple apps, each with their own CSS and JS files, you mightn't want to throw them into one single /static/ folder. It might be useful to put them in subfolders of the apps they belong to:
/app1/static/ # Specific static folder
/app2/static/
/media/
/static/ # Root static folder
Now, your webserver/development server is only looking for static files where you told it to look (i.e. the root static folder) so you need to collect all the files in the subfolders and copy them to the root static folder. You could do this by hand, but django provides a command to do this for you (this is the whole point of the static app)
./manage collectstatic
Why have you made the MEDIA_ROOT setting blank? It needs to be the path to your media directory. Since, as you say, your media is in a subdirectory called media, you should put that in MEDIA_ROOT.
I followed timmy procedure but I got an error that No module name django.views. When I use import django.views in my virtualenv everything works fine i.e It's not an issue with the import of library.
However, I was able to solve this problem by following this procedure in my main urls file
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
https://docs.djangoproject.com/en/dev/howto/static-files/
I had the same problem so I added these lines
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'', include('blog.urls')),
url(r'^admin/', admin.site.urls),
url(r'^cadmin/', include('cadmin.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in urls.py in the Django project configuration directory. more information :https://overiq.com/django/1.10/handling-media-files-in-django/
In your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS.Otherwise the MEDIA_ROOT won't work when you use it in the templates.
I am using Django 1.10. And my media folder is 'uploads'
This is the configuration in my settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
And in the template I put the name o my MEDIA_URL before de object.name instead object.url like this:
<img src="uploads/{{ imagen_identificativa.name }} " alt="{{imagen_identificativa}}">
And it works for me.
I hope this helps.
For Django version 3 I used the following:
from django.conf import settings
from django.urls import re_path
from django.views.static import serve
# ... the rest of your URLconf goes here ...
if settings.DEBUG:
urlpatterns += [
re_path(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
my settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
STATIC_URL = '/static/'
here is a documentation link https://docs.djangoproject.com/en/3.1/ref/views/
In case you are using Django REST with some dev server don't forget to update your dev proxy settings to redirect /media to Django backend
Here is another alternative:
Set your media configs something like this inside 'settings.py':
#Set media path
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Lets say I have a modal called person with image filed like below:
class Person(models.Model):
name = models.CharField(max_length = 30)
photo = models.ImageField(upload_to = 'photos')
Now here upload_to path we are taking about is inside the MEDIA_ROOT folder. In my case a media folder will be created inside which photos folder will be created and our media here will be dumped.
So now in my template I do something like this:
<img src="{{ person.photo.url}} />
So in short, you got a field, use it like this:
src ={{ object.field.url}}
Hope that helps! Happy Coding!