Django settings issue - django

Can any one tell me what is the issue in finding the media directory.In the templates when i say /media/images/logo.jpg It is unable to find the /media directory
The /media directory is in /home/project/myproject
Can any one tell me how to resolve this issue
I have the follwoing in my settings.py file
MEDIA_ROOT = '/home/project/myproject/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
The following is in myproject.wsgi file
sys.path = ['/home/project/lib/python2.6/django/', '/home/project/lib/python2.6','/usr/local/lib/python2.6/site-packages','/home/project/myproject'] + sys.path
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
application = WSGIHandler()

But you've set MEDIA_URL to ''! So why are you looking for images in \media?
If you want images to be in \media, you should set MEDIA_URL to that. Although you'll need to set ADMIN_MEDIA_PREFIX to something else.

MEDIA_ROOT is where files served at MEDIA_URL are resolved from. Users that are requesting static files can't hit your file path (MEDIA_ROOT), but they can request resources from a URL (MEDIA_URL). You need to define the MEDIA_URL, and you need to ensure that it is different to ADMIN_MEDIA_PREFIX.

Related

How To Serve media Files In Production

I have a Django project which sends automated e-mails with attached pdfs to users. At the moment I just have a normal /media/ folder with the pdf in it which the code points to. This works in development but throws a server error in production.
My question is how do I server media files in production? I have read a lot about it but can't find exactly what I'm after.
I use collectstatic in my production environment which works for static files, I'd expect something similar for media files.
urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('page.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static_media")
views.py (that sends the file)
file_path = os.path.join(settings.STATIC_ROOT+'\\pdf\\free_pdf.pdf')
...
msg.attach_file(file_path)
passenger.wsgi
import os
import sys
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
SCRIPT_NAME = os.getcwd()
SCRIPT_NAME = '' #solution for damn link problem
class PassengerPathInfoFix(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
from urllib.parse import unquote
environ['SCRIPT_NAME'] = SCRIPT_NAME
request_uri = unquote(environ['REQUEST_URI'])
script_name = unquote(environ.get('SCRIPT_NAME', ''))
offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0
environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0]
return self.app(environ, start_response)
application = get_wsgi_application()
application = PassengerPathInfoFix(application)
application = WhiteNoise(application, root='/home/mysite/mysite/static_files')
(this code is from when I abandoned the media folder and was trying to just serve it with my static files)
My proj structure:
|project
|__app
|__static
| |__app
| |__style.css
|__media
| |__app
| |__pdfToBeSent
|__static_files (generated by collectstatic)
|__media_files (i created this)
collectstatic also doesn't copy my projects media files into media_files, I have been copying them in there myself (unsure about this).
I have also tried moving the media file to every possible location in my project
I am also serving my static files with whitenoise.
Thank you.
Since I was in a similar situation (on the same hosting, A2Hosting), I will try to share my understanding of the problem and the solution I opted for.
Pardon me if I may seem presumptuous in this presentation, I'm simply trying to retrace all the points that represent the flow of thoughts that led me to this solution.
A small premise: if with "media files" you intend multimedial files, such as images and so on, I think you shouldn't use the Django media folder as it's designed to serve files uploaded by the users.
Not knowing if your PDFs are indeed uploaded by some user or not, I'll try to expose my solution anyway.
When in a production environment, Django isn't going to serve static and media files.
For the former I too used WhiteNoise, while for the latter the approach is different (at least on a shared hosting base).
When we set Debug = False in settings.py I suspect that the media folder, created along with the Django project, becomes somewhat unreadable/unaccessible (I cannot tell if by the hand of Django or by the hand of the hosting, or a conjuction of the two).
The official method to handle media files is indeed to rely on an external storage service (like Amazon S3), but this solution isn't suitable for budget limited scenarios.
In my situation, I had the Django app running on a subdomain related to my main domain.
Principal domain: www.mydomain.com
App domain: subdomain.mydomain.com
Leaving the media folder created with the Django project where it was, I created another one in the following unix path:
/home/A2hosting_username/subdomain.mydomain.com/media
Then, in settings.py I changed the MEDIA_ROOT variable from:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
to:
MEDIA_ROOT = '/home/A2hosting_username/subdomain.mydomain.com/media'
After that, in the model.py class used to define the database and interact with it, I specified the path to the uploaded media (videos, in my case) in this way:
class Video(models.Model):
name = models.CharField(max_length=50)
path = models.FileField(upload_to="../media/videos", null=True, verbose_name="")
Since we don't have access to the Apache config file, it may be useful to edit the .htaccess file (relative to subdomain.mydomain.com) in the following way, to prevent the browser to "time out" when the uploaded file is somewhat heavy:
<ifModule mod_headers.c>
Header set Connection keep-alive
</ifModule>
I hope this can be of any help.

Django how to display img in template by setting MEDIA_ROOT

here is my settings
MEDIA_ROOT = 'upload/'
MEDIA_URL = '/upload/'
where the path of upload folder is PROJECT_ROOT/myapp/upload.
I successfully upload a file a.jpg to that folder, but in the render page it shows that /upload/a.jpg not found
I'm confused about the media root setting. I think it's similar to STATIC_URL,
my static url setting is like this:
STATIC_URL = '/static/
and the path of static folder is PROJECT_ROOT/myapp/static
and files like /static/a.css can ben rendered successful in web pages.
media_root is the absolute path of the folder where your media files are being stored. 'upload/' is not an absolute path.
If you're storing your media files locally (development server) it would be something like (on windows)
c:\my_app_path\media
You can hard code it or you can use the os.path.join command :
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
more informations here
Francois

MEDIA_ROOT: shall I hardcode the path or use os.path.join?

Django 1.11
The documentation shows that we should place, say, images to
/var/www//media/
https://docs.djangoproject.com/en/1.11/ref/settings/#media-root
But in the book "Two Scoops of Django" they recommend:
# Configuring MEDIA_ROOT
# ’DONT DO THIS! Hardcoded to just one user's preferences
MEDIA_ROOT = "/Users/pydanny/twoscoops_project/media"
And then suggest their way:
root = lambda *dirs: join(abspath(BASE_DIR), *dirs)
# Configuring MEDIA_ROOT
MEDIA_ROOT = root("media")
Do you accept the way Two Scoops of Django recommends?
In this case MEDIA_ROOT will be inside the project itself. This is bad, I think. This is somehow a mix of code and user data.
So, I like what the documentation of Django recommends: just hardcode a path to /var/www/example.com/media/.
MEDIA_ROOT is not even STATIC_ROOT. Static files are collected from inside the project. And they contain something which is more or less (CSS) a code. Whereas user uploaded files are definitely the data, not the code.
Could you comment? What your MEDIA_ROOT looks like?
Shall I use different MEDIA_ROOTS for my local machine and the production serve?
I once used following :
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
This will automatically detect the absolute path to the settings.py file and create media_root path.

How to use pdf.js with django

pdf.js in in my static files(as shown below):
/static/js/pdf.js
And i am able to display a pdf located in static folder(as shown below):/static/sample-pdf.pdf
but i want to be able to show a pdf located in my media folder(as a pdf should be stored as a media file in django)
media folder is in same directory as of static folder(as shown below):
project/static andproject/media
Is it possible ?
Do ask if more clarity is required.
This will display your file in the html page from the directory
<iframe src="../media/sample-pdf.pdf" id = "pdf" style="width:1500px; height:1500px;" frameborder="0"></iframe>
check console of browser to check the path is right if its not showing. Its that much simple
Try setting your MEDIA_ROOT and MEDIA_URL in your settings.py and see if it works. Open up settings.py and add this:
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
# MEDIA_ROOT is used when users upload media.
MEDIA_ROOT = '/home/absolute/path/to/your/media/folder'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'
Then, you may also need to add this in your URLs.py:
from . import settings
import django.views.static
url(r'^(.*?)media/(?P<path>.*)$', django.views.static.serve,
{'document_root': settings.MEDIA_ROOT}),

Django static media files are not coming through

I cannot, for the life of me, get my static media files to come through on my local test machine in one particular project, though I've had no problem with a few other Django projects.
I'm using Django 1.1.1 and a Windows XP environment.
My settings.py looks like this for the media-hosting stuff:
ROOT_PATH = os.path.dirname(__file__)
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(ROOT_PATH, 'site_media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/site_media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
And it's looking in here:
http://127.0.0.1:8000/site_media/schedule/img/add.png
And the file is in the site directory along the lines of this:
c:\django\project_file\site_media\schedule\img\add.png
But for some reason the image still ain't showing up.
Any advice?
Your media root should be fully specified; define your MEDIA_ROOT as follows.
ROOT_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(ROOT_PATH, 'site_media')
Did you read this documentation about static files; you should also add extra route configuration to your urls.py to make sure that requests to the static content are handled correctly.
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),