MEDIA_ROOT django read and delete - python

I'm working on a Django application, which permits to manage music files (upload, read, delete, ...).
I'm using MEDIA_ROOT system for the music uploads, which works perfectly !
But, to read or delete a file in MEDIA_ROOT, I don't know ... (except with variable in script..).
For example, if I need to read a music with Mplayer, my actual solution in views.py :
media_root = "/home/music/"
command = ("sudo /usr/bin/mplayer "+media_root)
path = music.path
p = subprocess.Popen(command+str(music.path), shell=True)
Is there any (secure) way to access to the MEDIA_ROOT from views.py / models.py ??
Thanks

You can access the settings by simply doing
from django.conf import settings
settings.MEDIA_URL
https://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code

Related

How do you run a python script (.py) on an uploaded file in django

I have a question regarding handling downloaded files on Django. I have created a form that allows users to upload a file (XML Format). It is then saved in the media folder (MEDIA_URL). I have also created a 'Parser.py', a script that will find stuffs using Element Tree and will insert it to an SQLite database.
My question is where do I need to put this 'Parser.py' script so it can parse the uploaded file and insert the data to the database. Is it with the upload button or maybe in the views during the request?
I am assuming you have setup MEDIA_URL in your settings
To access the MEDIA_URL in your parser use below code.
from django.conf import settings
media_url = settings.MEDIA_URL
path_to_the_file = media_url + "/uploaded_file.xml"

Django sorl-thumbnail don't store files in my app

I read several topics here about this problem, but I can't manage to resolve it. Everybody asks if the MEDIA_ROOT config is okay, and other answer "yes sure!" But I did not find a real explanation, so:
I can see the generated filename (from db) in my template (a pdf genreated by weasyprint) :
/media/ cache/92/00/9200d02288657e7accae5666d37188a1.jpg
The object.exists in the thumbnail template tags returns, without surprise, False.
The file isn't generated.
In my settings.py I have this config :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
That worked fine with a basically FileUpload field.
I think I just don't understand the path configuration of MEDIA stuff.
Some explanations on good practices about dealing with MEDIA will be welcome !
EDIT : I uninstalled sorl-thumbnail and now use easy-thumbnails.

Django STATIC_URL clarification

I have read other topics on stackoverflow and on the django website, but I am still confused.
These are my configurations:
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATIC_URL = '/static/'
When I run manage.py collectstatic , my static files will be collected at myproject/assests/
I will store a default profile photo (for using with my models) here: myporject/static/images/default_profile_photo.png, so when I run collect static, it will be coppied in myproject/assets/images/default_profile_photo.png
Everything fine so far.
On my models.py I have a field:
class UserProfile(models.Model):
photo = models.ImageField(upload_to = get_upload_file_name,
storage = OverwriteStorage(),
default = 'path/to/my/default/image.jpg'))
My main question is: what path should I set to this default atribute? should I benefit from the STATIC_URL somehow?
Other questions: How can I user here the STATIC_URL from settings.py? and what is the usage of STATIC_URL? where and how can I see the effect between using STATIC_URL='/static/' and STATIC_URL='/wtf/'
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'static', 'templates'),
for each "os.path.dirname( )" I have one more within the following, which corresponds to a parent directory, so in my example I have four of them, it clarifies the root folder as being 4 folders above the current directory.
Files that are uploaded always go in a subdirectory of MEDIA_ROOT and are referenced from MEDIA_URL.
For any FileField (like ImageField), you simply give the subdirectory that will be used to store the files that are uploaded to this model.
If you have MEDIA_ROOT as '/foo/bar/uploads/', then in your models you have this:
class Foo(models.Model):
photo = models.ImageField(upload_to='photos')
Then all photos uploaded will be stored in /foo/bar/uploads/photos/.
Unlike collectstatic, there is no command to manage media files. You have to deal with them on your own.
Now on setting a default value; in addition to a path, you can add the name of a callable (a function), that is called whenever an instance of the object is saved. You can exploit this:
import os
from django.contrib.staticfiles import finders
from django.config import settings
def get_default_photo_path():
results = finders.find('/default/image.jpg')
if results:
return os.path.join(settings.STATICFILES_DIRS[0], results[0])
class Foo(models.Model):
photo = models.ImageField(upload_to='photos',
default=get_default_photo_path, null=True)
Now, whenever a new object is created, the default value is the static file path to /default/image.jpg. If for some reason this file doesn't exist (for example, you forgot to add it), None will be returned. In other to store that, you have to set null=True.

django ImageField not uploading the file

So i've been googling this issue for the past hour and can't come up with a solution. Basically this is it: in my model.py i have a class that has this
class Case(models.Model):
zoomOutImage = models.ImageField('Label', upload_to="zoomOutImage")
and in my settings.py i have my media URL/ROOT set up like this
MEDIA_ROOT = os.path.join(os.path.abspath(''),'app/static/ds/')
MEDIA_URL = '/static/ds/'
which from the webserver should serve out like this:
http://127.0.0.1:8000/static/ds/zoomOutImage/actinic_granuloma_3.jpg
I've installed PIL (inside virtualENV) and there are no errors in uploading, the only issue is when i try uploading the file via the admin panel nothing happens. No errors nothing. The file just simply doesn't get uploaded to the zoomOutImage folder by the development server. Can anyone point me towards why?
I guess your file is in a subdir of your root, subdir named 'zoomOutImage'. Or even a file called like that in the root. I remember putting a function call in the upload to string. That function creates a path and filename, using os.join and the filename from the instance. Doing this by head, no example code available right now. But must be able to google this.
Look here https://stackoverflow.com/questions/1190697/django-filefield-with-upload-to-determined-at-runtime
And by the way, I totally disagree with your answer, you should NEVER use absolute paths in your settings! See this answer use css in django 1.4 development for how to use the correct settings and refer to your Project PATH
EDIT (after reading your own answer)
Guess you are missing this first step:
this is the path to your settings.py file:
SETTINGS_DIR = os.path.dirname(os.path.realpath(__file__))
and than this is the path to your project dir: (I Am using buildout, so call it buildout, but it's the root of your project):
BUILDOUT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '..'))
and from there on you can define everything you want:
STATIC_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'static')
STATIC_URL = '/static_media/'
MEDIA_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'media')
MEDIA_URL = '/media/'
and in your template file refer to the image like:
<img src="{{MEDIA_URL}}{{ case.zoomOutImage }}" width="100%">
when your object given to the template is called case
about your question of the urls.
you should add this:
if settings.DEBUG:
urlpatterns += patterns('',
(r'', include('staticfiles.urls')),
)
and see the link above to the question about using css, it's the same problem, but there for finding the css files during development. It's all about the static file places.
import os
# get abspath
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
MEDIA_ROOT = rel('media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = '' #if only your static files are in project folder
STATICFILES_DIRS = ( rel('static'),) #if only your static files are in project folder
use this settings, and everything will work
so i finally solved my problem. For anyone having this issue in the future do the following:
if you're trying to serve static media files locally on the development server use absolute paths for MEDIA_ROOT and MEDIA_URL.

Django: Serving admin media files

I am trying to serve static files from another domain (sub domain of current domain).
To serve all media files I used this settings:
MEDIA_URL =
'http://media.bud-inform.co.ua/'
So when in template I used
{{ MEDIA_URL }}
it was replace with the setting above. Now I am trying to serve admin media files from the same subdomain, I changed the settings this way:
ADMIN_MEDIA_PREFIX =
'http://media.bud-inform.co.ua/admin_media/',
and expected that all calls to media from my admin site will be made to this url.... But actually it didn't work this way, I still see paths to CSS made as following:
http://bud-inform.co.ua/media/css/login.css
Could you suggest how to serve admin media files correctly
MEDIA_URL and ADMIN_MEDIA_PREFIX are two different things. One is the location of your media files, while the other is the location of the django admin system's media files.
You have to make sure that the ADMIN_MEDIA_PREFIX points to somewhere where you're actually serving the admin media. Django doesn't handle that step for you.
The django admin media is at django/contrib/admin/media/. Copy or symlink that directory somewhere publicly visible and set ADMIN_MEDIA_PREFIX to reflect where you put it.

Categories

Resources