Login

Link Media Command

Author:
elwaywitvac
Posted:
September 19, 2008
Language:
Python
Version:
1.0
Score:
2 (after 4 ratings)

A command for manage.py which scans through installed applications the way admin.autodiscover does, just looking for media folders. It then creates a symbolic link to the media under MEDIA_ROOT/app_name.

Usage: save in an apps management/commands folder and run with "python manage.py linkmedia"

Only works on *nix systems, but there should be an equivilent way to do this with windows using .lnk files.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    help = """
Removes all symlinks in MEDIA_ROOT and then scans all installed applications for a media folder to symlink to MEDIA_ROOT.

If installed app has a media folder, it first attempts to symlink the contents
    ie:   app/media/app_name -> MEDIA_ROOT/app_name
    
If the symlink name already exists, it assumes the media directory is not subfoldered and attempts:
    ie:  app/media -> MEDIA_ROOT/app_name"""
    
    def handle_noargs(self, **options):
        from django.conf import settings
        import os
        
        media_path = settings.MEDIA_ROOT
        for d in os.listdir(media_path):
            path = os.path.join(media_path,d)
            if os.path.islink(path):
                os.remove(os.path.join(path))
                print " - removed %s" % path
        
        for app in settings.INSTALLED_APPS:
            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
            if 'media' in os.listdir(app_path[0]) and os.path.isdir(os.path.join(app_path[0],'media')):
                app_media = os.path.join(app_path[0],'media')
                try:
                    for node in os.listdir(app_media):
                        os.symlink(os.path.join(app_media,node), os.path.join(media_path,node))
                        print " + added %s as %s" % (os.path.join(app_media,node), os.path.join(media_path,node))
                except OSError, e:
                    try:
                        os.symlink(app_media, os.path.join(media_path,app.split('.')[-1]))
                        print " + added %s as %s" % (app_media, os.path.join(media_path,app.split('.')[-1]))
                    except OSError,e:
                         print "ERROR: cannot add media from %s" % app

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.