dimanche 29 juillet 2018

How to get Filename and Filepath in Django based on a Model containing Fileupload?

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__"

A.K.A How do i get uploaded_file_name in views.py, I'm reading in various QnA at S.O that this is related to FileDescriptor but can't find how exactly also, print(Email.uploadcsvfile) gives <django.db.models.fields.files.FileDescriptor object at 0x03F7DF90> as output.




Aucun commentaire:

Enregistrer un commentaire