Django not recognizing the MEDIA_URL path? - python

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.

Related

Django | Cannot access URLs without a trailing "/"

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.

URL for Static files in Django Project

I am running Django project at suburl like www.example.com/django . Everything is working fine but my static files are not working on this suburl since they the url they are taking is main like www.example.com/static/path_to_files but it should take the url as www.example.com/django/static/path_to_files.
This can be the case for other urls too because I think whenever I use any url for any link it must take the hostname with the suburl like www.example.com/django instead of www.example.com .
you can also see this question of mine for more information about server configuration files.
In settings.py try:
STATIC_URL = '/django/static/'
More information here: https://docs.djangoproject.com/en/dev/howto/static-files/
You can serve them manually during development by adding the lines to urls.py:
urlpatterns = patterns('',
# Media files
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}
),
# Static files
url(r'^static/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, 'show_indexes': True}
),
)
Don't use this in production, and read the doc, its well explained.
Define MEDIA_URL and STATIC_URL in settings.py
MEDIA_URL = /django/media
STATIC_URL = /django/static
Then prepend this variable while defining url in templates:
media
<img src="{{ STATIC_URL }}/path_to_static_file" />
Now you can use these variables wherever you want to create urls.

ImageField in Django 1.5.4 -- dealing with the images' paths

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.

Django cannot find my media files (on development server)

The media is currently on my local development machine.
My MEDIA_ROOT, MEDIA_URL, ADMIN_MEDIA_PREFIX and are specified as below:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MEDIA_URL = '/media/'
SITE_URL = 'http://localhost:80'
ADMIN_MEDIA_PREFIX = '/media/admin/'
There is no 'admin' folder but that shouldn't make a difference I don't think.
In the urls.py file I have:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
I am at a loss as to what I should do to get it working.
[I am trying to learn django and am working with an existing project that's pretty hairy]
You're mixing and matching pre and post-Django 1.3 static file handling. Originally all static files were served from MEDIA_URL, but Django 1.3 introduced the staticfiles contrib package and the associated STATIC_ROOT and STATIC_URL settings. django.views.static.serve utilizes the new staticfiles app, which you haven't set up.
Assuming you're running Django 1.3, first, you'll need to add 'staticfiles' to your INSTALLED_APPS. Then, you'll need to define STATIC_ROOT and STATIC_URL. The standard location is a project-root level directory named "static".
You'll also need to add the staticfiles template context processor:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
)
This will make the STATIC_URL variable available in your templates, so you can reference your resources with something like {{ STATIC_URL }}css/style.css
All your static resources will also need to go into an app(s)-level directory named "static". The actual project-root level "static" directory is never directly used. It's simply the place where the collectstatic management command dumps all your static resources for use in production.
If you want project-wide static resources (not tied to any one particular app), you'll need an entirely separate directory (i.e. not the same as MEDIA_ROOT or STATIC_ROOT). I tend to use one named "assets". You'll then need to tell Django to look in here for static resources as well with the STATICFILES_DIRS setting:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'assets'), # or whatever you named it
)
MEDIA_ROOT/MEDIA_URL are now only used for user uploads (e.g. any file created through FileFields and ImageFields, so you still need it, but you won't ever manually store anything there.
When you reach production, your webserver will need to serve both MEDIA_ROOT and STATIC_ROOT at MEDIA_URL and STATIC_URL, respectively. You'll also need to run:
$ python manage.py collectstatic
To make Django compile all your static files into the directory specified by STATIC_ROOT.
works with django 1.8 - 1.11:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development
note that Django documentation states that this is
not suitable for production use
(obviously unless you use if settings.DEBUG: part)
On development server, this page may help you.
https://docs.djangoproject.com/en/1.2/howto/static-files/
By adding follow code to urls.py:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}),
)
With python-django 1.7 I used
if settings.DEBUG:
urlpatterns = patterns('',
(r'^$', 'blenderx3d.first_step.views.index'),
(r'^media/(?P<path>.*)$','django.contrib.staticfiles.views.serve'),)

include image files in Django templates shows broken link?

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.

Categories