blacklight blacklight - 8 months ago 35
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)
@property
def filename(self):
return os.path.basename(self.audio_file.name)
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)
d.audio_file.name


but it only shows this : ''

Answer Source

I think you should use next things:

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

self.audio_file.path instead of self.audio_file.name

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