Tms91
Tms91

Reputation: 4164

How can I implement a File_name field that excludes my file path and contains only the file name [Django models]

I am developing an app in Django. In my template I have a fileform that allows users to store files in a model, they are stored in my media_root/uploaded_files/ directory:

class my_model (models.Model):

    file_obj = models.FileField(upload_to='uploaded_files/', blank=False, null=False)

    def __str__(self):    
        return  "%s"  %  (self.file_obj)  

But in my admin section, accessing the model my_model I get file names like:

• uploaded_ files/file_1
• uploaded_ files/file_2
• uploaded_ file /file_3

While I want:

• file_1
• file_2
• file_3

How can I implement a File_name field that excludes “uploaded_ files” and contains only the file name?

Upvotes: 0

Views: 40

Answers (2)

Tms91
Tms91

Reputation: 4164

SOLVED:

In my admin.py:

class my_modelAdmin(admin.ModelAdmin):

    def file_name(self):
            import os
            return os.path.basename(self.file_obj.name)


    list_display = [file_name]

Upvotes: 0

dirkgroten
dirkgroten

Reputation: 20682

As explained here, the name property returns the path of the file relative to your storage root.

If you want to get just the name of the file, use os.path.basename() to extract the name.

Upvotes: 1

Related Questions