blacklight blacklight - 1 year ago 52
Python Question

How to get the name of the file from the filefield?

I know this question has been asked a lot of times but I am not able to find a nice solution to this. Here is my model:

class Song(models.Model):
song_title = models.CharField(max_length=200, null=False, blank=False)
audio_file = models.FileField(default='', null=True,blank=True)
def filename(self):
return os.path.basename(
def __str__(self):
return self.song_title

I have done all this, but I am still not able to get the file name.So in the admin page, I uploaded a new song with the name : song.mp3. In the admin panel , it shows like this :

Currently: ./song.mp3

I need to get the name song.mp3 , how can I do so? I tried doing this in the python shell:

d = Song.object.get(pk=1)

but it only shows this : ''

Answer Source

I think you should use next things:

def filename(self):
    return self.audio_file.path # os.path.basename(self.audio_file.path)

self.audio_file.path instead of

and read more about managing files Django managing files it's will help you in future;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download