问题
I have successfully deployed my Django project in openshift. But I need to be able to serve files that are uploaded by users. I user MEDIA_ROOT and MEDIA_URL for that. I followed this tutorial here, but nothing happened. I had to change MEDIA_ROOT because the one suggested there isn't correct i think. So my MEDIA_ROOT looks like
MEDIA_ROOT = os.path.join(os.environ.get('OPENSHIFT_DATA_DIR', ''),'media')
MEDIA_URL = '/media/'
I added the .htaccess in /wsgi folder with as it says in the article
RewriteEngine On
RewriteRule ^application/media/(.+)$ /static/$1 [L]
and created the build script to make symbolic link of the media in static as the article says.
#!/bin/bash
if [ ! -d $OPENSHIFT_DATA_DIR/media ]; then
mkdir $OPENSHIFT_DATA_DIR/media
fi
ln -sf $OPENSHIFT_DATA_DIR/media $OPENSHIFT_REPO_DIR/wsgi/static/media
In my urls.py I have added the
urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_URL)
but I still can't serve them. I also tried not to include the django static method in urls.py but the same result.
In another tutorial .htacces is placed inside static folder. Am I doing something wrong?
回答1:
Just for others to know, I solved my problem by correcting the RewriteRule adding media folder to the second part of the rule, so it became
RewriteEngine On
RewriteRule ^application/media/(.+)$ /static/media/$1 [L]
Hope it helps others.
回答2:
The problem is your media url. The symlink is created at wsgi/static/media, then your MEDIA_URL need is MEDIA_URL = '/static/media/'
First step, on build script .openshift/action_hooks/build:
if [ ! -d $OPENSHIFT_DATA_DIR/media ]; then mkdir $OPENSHIFT_DATA_DIR/media fi
ln -sf $OPENSHIFT_DATA_DIR/media $OPENSHIFT_REPO_DIR/wsgi/static/media
Second step: In your settings:
MEDIA_URL = '/static/media/'
if ON_PAAS:
MEDIA_ROOT = os.path.join(os.environ.get('OPENSHIFT_DATA_DIR'), 'media')
else:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
回答3:
I've had the same problem but Apostolos' solution above hasn't solved the issue: when I try to access http://<domain>/media/<file>
it still doesn't work.
However it does work in another way. if I try to access the same file as if it was a static using http://<domain>/static/media/<file>
then it does work. This happens even without employing Gpzim98's workaround. I think the reason is simply that the media files are now accessible through the symbolic link. In other words media files don't get served but you can now pretend they are static files.
Would be very keen to understand what is going on and how to resolve this problem fully (if it can be done) and be able to serve media files directly through the MEDIA_URL.
Thanks
来源:https://stackoverflow.com/questions/23807969/django-serving-media-files-user-uploaded-files-in-openshift