pythondjangowebdjango-modelsdjango-views

How to get Filename in DjangoWebApp based on a Model containing FileField?


I making a email delivery WebApp, I have an Email Class with uploadcsvfile to upload the .csv contact file from the user's computer to server at location CONTACT_DIR, what I'm unable to figure out is how to get the saved contacts_some_char.csv name in my views.py, the purpouse of getting it's name is so that I can parse the email list and send email to them.

I have my model.py as follows :

class Email(models.Model):
    fromemail = models.EmailField(blank = False, max_length = 254)
    uploadcsvfile = models.FileField(upload_to = 'Contacts', blank = False)
    subject = models.CharField(blank=False,max_length = 254)
    bodyHeading = models.CharField(blank = False,max_length = 254)
    bodytext = models.TextField(blank = False)
    name = models.CharField(blank = False,max_length = 254)

Here is my views.py :

def index(request):

    if request.method == 'POST':
        email_form = EmailForm(request.POST, request.FILES)
        if email_form.is_valid():
            email_form.save(commit = True)
            print(Email.uploadcsvfile)
            contacts = Contacts()
            #path = settings.CONTACT_DIR
            f = open(settings.CONTACT_DIR+"/"+str(uploaded_file_name))
            csv_f = csv.reader(f)
            Emails = []
            Names= []
            L_Names = []
            for x in csv_f:
                Emails.append(x[0])
                Names.append(x[1])
                L_Names.append(x[2])
            f.close()
            contacts.ListOfEmails = json.dumps(Emails)
            contacts.ListOfFirstNames = json.dumps(Names)
            contacts.ListOfLastNames = json.dumps(L_Names)
            contacts.save()

Here is forms.py for the same :

from django import forms
from dcsvreader.models import Email

class EmailForm(forms.ModelForm):
    class Meta():
        model = Email
        fields = "__all__"

In short, how do i get uploaded_file_name in views.py, having gone through various Q&A in S.O. that this is related to FileDescriptor but can't find how to exactly do this, also print(Email.uploadcsvfile) gives <django.db.models.fields.files.FileDescriptor object at 0x03F7DF90> as output.


Solution

  • request.FILES is a dictionary-like object containing all uploaded files and the uploadcsvfile is the key in which you are making a POST request. Hence, request.FILES['uploadcsvfile'] will hold the particular file as InMemoryUploadedFile and it has a variable .name which holds the filename

    Try this,

    file_name = request.FILES['uploadcsvfile'].name
    


    Reference
    uploadfile.name
    request.FILES