Serving media files in Django - django

I am running Django in development. In settings.py I have set up the MEDIA_URL
MEDIA_ROOT = os.path.join(BASE_DIR, 'fileuploader/uploaded_files')
MEDIA_URL = 'fileuploader/uploaded_files/'
Then in ursl.py I have,
if settings.DEBUG:
urlpatterns += patterns('', url(r'^media/(?P<path>)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT,}),)
As far as I understand this should mean that any url media/filename will serve the file instead just requesting it.
In the template, through the model i am able to get to the file name and url. But i can't make this into a linkable path to download the file.
<p>File URL link media{{ item.upload}}</p>
Incidently item.upload and item.upload.name produce the same string.
The file name in the filestore is ./TESTFILE.txt Do I need to strip the './' at the beginning?
Commit 26 is the project https://github.com/shanegibney/djangoForum
Thanks

I added the MEDIA_URL tag and this allows files to download.
<p>URL media{{ item.upload}}</p>
Also in urls.py to the end I added,
urlpatterns = [
......
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

How to Secure Django Media Files in Production

In my localhost server, I was able to restrict users from accessing pdf media files which they are not supposed to access given that they are not the uploader of the file or the admin of the system.
The problem is that when I tried to deploy my application, the restriction on my media files no longer works.
This is my urls.py
urlpatterns = [ path('media/pdf/<str:path>', views.pdf, name='pdf'), ]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
And my MEDIA_URL and MEDIA_ROOT in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Also my debug is still set to TRUE in deployment, could this also be the problem?

How to fix Django Summernote using relative path for src url in image integration?

I am new to the Django framework, and inherited a projet which I am trying to fix.
Right now my project runs in a docker at url localhost:8000 until deployment in on a remote server.
I have the django-summernote extension installed for fancy text editing and image integration, but it doesn't work as expected:
Summernote Editor in Django admin works fine, and correctly displays uploaded images
But on my content pages, the html integration of my provides an incorrect src url (which return an error ofc)
src="/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png"
The expected html integration should be :
src="http://localhost:8000/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png"
I checked and the image file does exist in the folder, the expected url below does actually shows the picture alright as well.
The rest of the website uses images integration just fine when not related to summernote.
I figure this has something to do with settings.py or even router (which tbh is still a bit complex in my head).
settings.py
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
...
path("summernote/", include("django_summernote.urls")),
]
Edit: running Django 3.1
For Django >= 1.7
Just add this into your
urls.py
urlpatterns = [
...
path("summernote/", include("django_summernote.urls")),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You no longer need if settings.DEBUG as Django will handle ensuring this is only used in Debug mode.
For Django <= 1.6
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Try this:
settings.py
MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = "/media/"
urls.py
urlpatterns = [
...
path("summernote/", include("django_summernote.urls")),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Static url goes after the regular page url

My static files only load on index page, but when navigating to another page like: examle_url/page, it returns a 404 error since it loads it like that: http://127.0.0.1:8000/categories/default/static/js/main.js, see the static loads after page
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '/static/base'),
)
urls.py "all my urls are in main directory and then i import views from apps"
urlpatterns = [
path('admin/', admin.site.urls),
path('profile/', profile, name="profile"),
path('', index, name="index"),
path('category/', category, name="category"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If it matters my load static files are all in theme.html file and is then extended in all other html files.
Any help will be greatly appreciated, thanks in advance!
You should prepend the STATIC_URL setting [Django-doc] with a slash:
# settings.py
# …
# with a leading slash
STATIC_URL = '/static/'
# …
If you do not do that, then the url will look like static/js/main.js. If the path does not start with a slash, then that is relative to path the current URL, and thus if the page is /categories/default, it will look at /categories/default/static/js/main.js.

Images from media folder is not displaying django template

I am having images in my media folder and I want to display them but Django is not displaying images other than static folder.
In my setting
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),]
MEDIA_ROOT = BASE_DIR
MEDIA_URL = '/media/'
In my urls.py after url pattern I added this
+ static(MEDIA_URL, document_root=MEDIA_ROOT)
In my templates
<img class="card-img-top" style="" src="{{result.object.thumbnail.url}}" alt=""></a>
<p>{{result.object.thumbnail.url}}</p>
It is showing the correct path but not showing the image, I am unable to figure out the problem. Thanks
Your MEDIA_ROOT have the path of the root of your project. You must join to it, the direcotry of your media. (I suppose media/ is the directory name where you upload all your media)
I think you should have your MEDIA_ROOT like that.
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_ROOT have root path of your project. MEDIA_URL must be correct. Check following
setting.py of your project
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py of project
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url('', include('app1.urls')),
url('home/', myapp_views.index)
] + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
I was facing same error from the last 5 days , follow django documentation, many tutorials but nothing work for me but finally I found the solution
I am showing the index.html on home means I have not given any endpoint in url of my app and project url file
app/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', 'views.index', name='index page'),
]
project/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url('', include('app1.urls')),
url('', myapp_views.index)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Rest of code remains the same and I changed the following in both files
app/urls.py
url('home/', 'views.index', name='index page'),
project/urls.py
url('home/', myapp_views.index)
That's work for me. Accept the answer if also work for you
This is a chunk of my HTTP logs from django v3.2 running wagtail. Looks as though django is trying to tell me where the missing media is but not able to. Because this is a thicket page with gallery sub-images of "featured pages" the view source in my browser doesn't reveal the image file attempt, but I am assuming it is the same issue as OP's with misconfigured MEDIA_ROOT. Strangely, not seeing any errors in the page's linked images when I bring the child page up in wagtail admin. Anyone have an idea why the missing image won't bubble up to the HTTP logs, or what causes the "media/not-found" substitution for the "real" item causing the 404?
[25/Aug/2021 20:28:53] "GET /static/wagtailadmin/images/bg-dark-diag.svg HTTP/1.0" 200 700
Not Found: /media/not-found
[25/Aug/2021 20:29:18] "GET /media/not-found HTTP/1.0" 404 3252
Not Found: /media/not-found
[25/Aug/2021 20:29:18] "GET /media/not-found HTTP/1.0" 404 3252

Accessing "Media" files in Django

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!