简体   繁体   中英

Edit URL variable in Django (remove first element from path)

I have a variable:

kid.image_url

which stored a url:

/media/pics/byson.jpg

I want to remove /media so that it contain just:

/pics/byson.jpg

I have just started to learn django. Any help will be appreciated : )

 stripped = '/media/pics/byson.jpg'.split('/')[2:]
 kid.image_url = '/'+'/'.join(stripped)

Consider using python os.path.split(path) and os.path.join functions. They work both on Windows and Linux. This way your code would be portable. See Splitting a Path into All of Its Parts . Below is working code

import os, sys

def splitall(path):
    allparts = []
    while 1:
        parts = os.path.split(path)
        if parts[0] == path:  # sentinel for absolute paths
            allparts.insert(0, parts[0])
            break
        elif parts[1] == path: # sentinel for relative paths
            allparts.insert(0, parts[1])
            break
        else:
            path = parts[0]
            allparts.insert(0, parts[1])
    return allparts


image_url = "/media/pics/byson.jpg"
image_url = os.path.join(*splitall(image_url)[2:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM