I am using Django 1.5.4 and I have a project with the following structure:
django_site
-django_site
-books # the app
-media
-images
-books
-authors
-static
-images
-templates
This is the necessary code:
# settings.py
MEDIA_ROOT = '/root/django_site/books/media/'
MEDIA_URL = '/media/'
# models.py
class Book(models.Model):
image = models.ImageField(upload_to="images/books/")
# urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^books/$', 'books.views.get_all_books'),
)
My problem is that, after adding the image via the admin site, if I click on the image link below the upload button a 404 page shows up, complaining the path does not exist.
The request URL is http://127.0.0.1:8000/media/books/media/images/book/out_of_control_1.JPG but in fact I want the result to be /root/django_site/books/media/images/out_of_control_1.JPG.
How do I fix that? Looking forward to your responses.
Since you seem to use the developpement server, I think your issue is related to this one : Django MEDIA_URL and MEDIA_ROOT
As explained in the answer, you have to set up a specific URL pattern for media handling when debug is set to True.
You can also have a look at the docs regarding this question.
Related
this is my first question so please point me to the right direction in case I miss something of importance ☺️
So my problem is the following:
I'm currently creating a website with Django, which is supposed to list a variety of projects from the database. Each project has a picture associated with it. The path to this picture is saved in the database (each picture is added as models.ImageField() to the projects model). In order to serve them, I added MEDIA_ROOT = os.path.join(BASE_DIR, 'main/media') to my settings.py and added the following snippet to my urlpatternsin urls.py: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now to the crux of it: Everything works fine, except I can't open my admin panel now. The media files are served as expected in the projects overview, but at soon as I try to open the /admin page, I get following error message:
Page not found (404)
“/Users/.../main/media/admin” does not exist
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Raised by: django.views.static.serve
as soon as I remove + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from my url patterns, the admin page works fine again, however the media files are not served anymore.
Can someone show me what I've broken here?
Thank you very much!
I had the same problem. I had a link on my site, that when pressed took me to admin panel.
The mistake was that I was missing a trailing slash.
This did not work:
Admin
This worked:
Admin
You might not have added the MEDIA_URL path in setting.py.
In your case:- add this to settings.py:- MEDIA_URL = "/main/media/". If it doesn't work, try removing one of the two corner slashes. Hope it will work.
I have a Django application where, for some reason, I cannot load my URLs without a trailing "/"
I have other Django applications I've made in practice where this hasn't been an issue, and I don't need one when I go to my Admin page, so I can't figure out what's setup wrong here.
Here's my main URLs file:
urlpatterns = [
path('app/', include('app.urls')),
]
Here's my app's URLs file:
urlpatterns = [
path('subapp/', views.subapp, name='subapp'),
]
And my views file:
def subapp(request):
return render(request, 'app/subapp.html', {'title': 'subapp'})
When I enter my URL as "localhost:8000/app/subapp/" it takes me to the correct page.
However, when I enter my URL as "localhost:8000/app/subapp" I get a 404 with the following debug error message: Directory indexes are not allowed here.
What am I doing wrong?
Please check APPEND_SLASH setting in the settings.py file.
Please also check that link:
django urls without a trailing slash do not redirect
For my specific usecase, it was because I needed to add the following to my settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
This fixed my issue.
I am having some problems with serving user uploaded files from my Django application:
from models.py:
class Picture (models.Model):
title = models.CharField(max_length=48)
date_added = models.DateTimeField(auto_now=True)
content = models.ImageField(upload_to='pictures')
From the Django admin the files get uploaded to the user_res/pictures/ folder.
from the project's settings.py:
MEDIA_ROOT = 'user_res'
MEDIA_URL = '/user_res/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
Every time I try to reference a static resource (namely css or js files), everything works fine using URLs such as
http://localhost:8000/static/<subfolder>/main.css.
However, I cannot access user uploaded files (which get created by the admin interface in the user_res/pictures folder with a relative URL such as
user_res/pictures/test.jpg
the URL is dynamically created with this line of code from a Django Picture model callable:
return '<img src="{}"/>'.format(self.content.url)
I have no dedicated url-s for either static or media files in the url.py file.
Does anybody have any idea as to how to make Django serve the media files? I understand that for live environments I will need to configure an http server to serve that particular directory, but for now I want to maintain a lightweight development suite.
Thank you.
Edit your urls.py file as shown below.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
edit your projects settings.py to look like:
#Rest of the settings
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
STATIC_ROOT = ''
STATIC_URL = '/static/'
Please read the official Django documentation about serving files uploaded by a user carefully. Link to docs: https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user
I think the url attribute returns a relative URL ( Django's FileField documentation ), so you should have:
return '<img src="{}"/>'.format(MEDIA_URL + self.content.url)
Relative URLs won't work, as a user visiting "http://localhost/books/" would be requesting "http://localhost/books/user_res/pictures/test.jpg".
All,
I've tried the tips found on the forum. Unfortunately i'm still stuck.
The image doesn't appear in the template.
As far as i've traced the errors now they are twofold:
1) one where the picture should appear there is still a broke link and an error message:
Failed to load resource: the server responded with a status of 404 (NOT FOUND),
**http://127.0.0.1:8000/Point3D/grafiek/laptop.jpg**
So it does go in the right path, but can't find the image.. Which is in my MEDIA_ROOT
or I receive:
Resource interpreted as image but transferred with MIME type text/html with:
**http://127.0.0.1:8000/Point3D/grafiek/**
2) The other error is that if i go to : http://127.0.0.1:8000/media/ i get:
Permission denied: /media/
maybe this has something to do with it.
For the rest i've followed roberts solution for now but without any luck..
Any help would be very much appreciated!
What's your template looking like? It's should be something like:
<img src="{{ MEDIA_URL }}Point3D/grafiek/laptop.jpg" alt="" />
I'm guessing the right path for your image should be http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg
Are you including {{ MEDIA_ROOT }} in your tag.
Also, make sure you are calling the template with a RequestContext object, because otherwise {{ MEDIA_ROOT }} will not be set in your template. Try using django.views.generic.simple.direct_to_template rather than django.shortcuts.render_to_response. Note that direct_to_template is called just like render_to_response except it takes request as the first argument.
from django.views.generic.simple import direct_to_template
# your view code here
return direct_to_template(request, 'path/to/template.html', **kwargs)
Assuming media on your file system is at:
/home/username/django-project/media/images/favicon.ico
In your settings.py, you should have:
import os
PROJECT_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.media',
)
Your project urls.py should also contain the following which should only work in DEBUG mode:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT.replace('\\','/')}, name='media'),
)
Your template should include media like the following:
<link rel="icon" href="{{ MEDIA_URL }}images/favicon.ico" />
Permission denied on /media/ is exactly what is supposed to happen, as otherwise every user of you page could view all the files in that directory (Would be the same as configuring Apache to allow Indexing of a Directory, which is, in allmost al cases, not what you want. Try accessing the file in your browser by pasting the complete url, (and include the media url in your path!):
http://127.0.0.1:8000/media/Point3D/grafiek/laptop.jpg
If that does not work, make sure you have Django or Apache configured to serve the static files you try to access.
edit:
And one more thing that could cause your trouble: /media/ is the default for the admin media url. If your admin media url and your media url are the same thats no good. Change that so your MEDIA_URL and your ADMIN_MEDIA_PREFIX are not the same.
So I'm trying to get TinyMCE up and running on a simple view function, but the path to the tiny_mce.js file gets screwed up. The file is located at /Users/home/Django/tinyMCE/media/js/tiny_mce/tiny_mce.js. I believe that /media/js/tiny_mce/tiny_mce.js is correct, as the development server has no access to files above the root of the Django project folder. In the rendered page, it says in the debugger that the javascript file was not found. This is because it was trying to look through /js/tiny_mce/tiny_mce.js without addressing the /media/ part of the pathname.
Anyway, here's the script snippet for the javascript in a template named 'simple.html'. <script type="text/javascript" src="{{ MEDIA_URL }}/js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
And this is what the vital parts of my settings is like.
MEDIA_ROOT = os.path.join(_base, 'media')
MEDIA_URL = 'http://127.0.0.1:8000/media/'
ADMIN_MEDIA_PREFIX = '/media/'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'tinymce',
)
It looks like your are using the debug server (your url is http://127.0.0.1:8000/...) . Did you install the static serve in your urls.py?
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),
)
The 'show_indexes':True options make possible to browse your media. Go to your medias root http://127.0.0.1:8000/media/ and see it there is something
You can either pass it to the template manually as others have suggested or ensure that you are using a RequestContext instead of plain Context. RequestContext will automatically populate the context with certain variables including MEDIA_URL and other media-related ones.
Example from docs:
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
It looks like ars has answered your real question… But you'll run into another problem: MEDIA_URL must be different from ADMIN_MEDIA_PREFIX. If they aren't, the ADMIN_MEDIA_PREFIX will take precedence. I usually fix this by changing ADMIN_MEDIA_PREFIX to /admin-media/.
Do you have the media context processor in your settings?
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.media',
)
You might also try putting the following in your settings to see if the debug messages reveal anything:
TEMPLATE_DEBUG = True
Please read the official Django DOC carefully and you will find the most fit answer.
The best and easist way to solve this is like below.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The related url is: https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user
Thanks a lot for your help everyone. I was able to solve it as
settings.py -->
MEDIA_ROOT = '/home/patrick/Documents/code/projects/test/media/'
MEDIA_URL = 'http://localhost:8000/media/'
urls.py -->
(r'^media/(?P<path>,*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
index.html -->
img src="/media/images/logo.jpg"
Again, thanks a lot, I was going crazy trying to find out how to do all of this. This solution worked for me on a Django version 1.2.5 Development server running Ubuntu 10.04.
I had a similar problem,
I have a one-page-app and Apparently I had a newbie mistake that made django miss my media path i had this:
url(r'^', home, name="home"),
instead of this:
url(r'^$', home, name="home"),
the missing $ made my url pattern miss my media url
I was also having the same problem, this is how I got it done.
If you are using a FileField in your model class instead of MEDIA_URL use .url member to access the url of your file.
For eg: something like this
href = "{{ some_object.file_name.url }}"
here file_name is the FileField in model class.