How to get uploaded file name from django id

Viewed 208

I simply wanted the exact file name which I have uploaded so that I can read the whole file and show content on the HTML page...

class newcodes(models.Model):
    user_id = models.AutoField
    fullname = models.CharField(max_length=200)
    codefile = models.FileField(upload_to ='programs/')//her is my codefile location in models

Here is my function for reading text but i can't get name of the uploaded file so i can't read the file

def showcode(request,id):
    programs=newcodes.objects.filter(id=id)
    print(programs)
    # f=open('media/')
    return render(request,"Codes.html")
1 Answers
programs=newcodes.objects.filter(id=id)

This will return the QuerySet. You need to get instead of filter:

program=newcodes.objects.get(id=id)

This will give newcodes object. From that you can get the uploaded file as :

program.codefile.name

If filename is along with the directory, simply split the file name like this:

import os
os.path.split(program.codefile.name)[-1]
Related