URL for Static files in Django Project - python

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.

Related

Django: serving user uploaded files

I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = "/media/"
When I access these files through my admin I get the following url displayed in my browser:
http://127.0.0.1:8000/media/filename.pdf
Hence what I tried is to give a link to the file in my HTML code :
File
But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error.
Adding localhost:8000/ before {{instance.docFile.url}} also didn't work.
Why isn't this working?What is the correct way to display link to my files?
Let me know if anything else is required.Thank you.
in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
Then in your template
File
If you want know refer the docs Manage static files
The error is coming because your file is not stored in media.it is stored in static but your database store media URL. change your MEDIA_ROOT (given below) and try to upload one more time
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Don't put slash
:
File
Please see the Django setting MEDIA_ROOT documentation to better understand what your trying to do.
First MEDIA_ROOT and STATIC_ROOT must have different values.
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
See static files documentation for more details.
Second, You need to add these settings to your base urls.py.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES in settings.py.
At the top of your HTML page add {% load static %} then to display your media:
<img src="{{ MEDIA_URL }}{{ docFile }}" alt="test">
Please take your time with the Django Documentation, trust me it will help and also checkout the File upload settings

django static files relative path does not work

I cahnged the static files defualt path
and added in url.py
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, "static")
It works fine for first level pages
like
/login
/admin
/dahboard
but static files does not load when I go to second level pages
/admin/users/
/admin/users/add/
How I can fix this problem
Make sure your STATIC_URL has a / at the beginning:
STATIC_URL = '/static/'
Otherwise, URL will be like <img src="static/thing.png" /> which can work on first level (since it will search from the root) but not when you are in subdirectories.
Be aware the serve method only work in DEBUG mode.

Django - Serving Media/Admin files in production with Apache/Webfaction

As it stands my STATIC files are served without issue using the configuration below.
In my settings.py:
MEDIA_ROOT = '/home/chronic88/webapps/media_media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/chronic88/webapps/static_media/'
STATIC_URL = '/static/'
static_media and media_media are both applications served by apache.
I can upload files via the admin and they show up inside the folder media_media, but they won't display on their pages. When I check the file paths in the page source they seem correct mydomain.com/media/image.png but they simply won't display. So, it seems the link is there but there is some problem communicating between apache and django that I can't put my finger on.
And my main urls.py:
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is the urls.py I'm using in prodution that works. I tried it without the last line in production but it gives the same result (files are uploaded but not displayable).
What am I missing?
If you configured your Apache to serve the static files from the respective root folders, you also have to run manage.py collectstatic (see docs).
To test static and media files I usually have this in my urls.py:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
)

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'),)

Django not recognizing the MEDIA_URL path?

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.

Categories