Python 2.7 - Access Javascript file object in Django

420
May 15, 2017, at 04:04 AM

I am building an app that sends multiple files as email attachments, using jQuery and Django 1.9.

I store the files in a buffer that the user can add and delete from, and sending them over a POST Ajax request as such:

            //Build the message
            message_buffer.forEach(function(entry){
                body += '\n' + entry;
            });
            var files = $.merge(attachment_buffer.photos, attachment_buffer.documents);
            var form = new FormData();
            form.append("csrfmiddlewaretoken", csrf_token);
            form.append("client_id", client_id);
            form.append("subject", subject);
            form.append("body", body);
            form.append("files", files);
            $.ajax({
                url: window.location.origin + '/dashboard/ajax/send_message',
                method: "post",
                data: form,
                processData: false,
                contentType: false,
                cache: false,
                beforeSend: function(){
                    //Block UI
                },
                success: function(data){
                    if(data.status == 'success'){
                        console.log(data);
                        //Show success and clear all the data stores.
                    } else {
                        console.log(data.message);
                    }
                },
                error: function(err){
                    console.log(err.responseText);
                }
            });

Problem is when i get this buffer (a list of JS file objects) in my django view, they are gotten as unicode and i dont know how to parse them.

I need to be able to attach the files to the django EmailMessage instance like this:

        for attachment in attachments:
            mail.attach(attachment.name, attachment.read(), attachment.content_type)

The Django view code is:

if request.method == "POST":
    client_id = request.POST['client_id']
    subject = request.POST['subject']
    body = request.POST['body']
    attachments = []
    if 'files' in request.POST.keys() and request.POST['files'] != '':
        attachments = request.POST['files']
    client = Client.get_client_by_id(request.user, client_id)
    if client:
        email_helper = EmailHelper()
        email_sent = email_helper.send_email_with_attachments(request, client, subject, body, attachments)

And the email method:

def send_email_with_attachments(self, request, client, subject, message, attachments, from_email=settings.EMAIL_HOST_USER):
    """
    Sends a simple text mail with attachments
    :param request:
    :param client:
    :param subject:
    :param message:
    :param from_email:
    :param attachments:
    :return:
    """
    # print type(encoding.smart_bytes(attachments))
    # # for attachment in attachments:
    # #     print json.loads(attachment)
    # #
    # return False
    try:
        mail = EmailMessage(
            self.clean_email_params(subject),
            self.clean_email_params(message),
            self.clean_email_params(from_email),
            self.clean_email_params([client.email]),
            reply_to=[from_email]
        )
        for attachment in attachments:
            mail.attach(attachment.name, attachment.read(), attachment.content_type)
        mail.send()
        try:
            # Log the sent email
            email_log = SentEmailsLog()
            email_log.user = request.user
            email_log.client = client
            email_log.subject = self.clean_email_params(subject)
            email_log.content = self.clean_email_params(message)
            email_log.to_email = str(self.clean_email_params([client.email]))
            email_log.from_email = self.clean_email_params(from_email)
            email_log.host_email = settings.EMAIL_HOST_USER
            email_log.attachments = 'No'
            email_log.save()
        except Exception, e:
            ErrorLogHelper.log_error(error_message=e, calling_function="EmailHelper.send_email_with_attachments")
        return True
    except Exception, e:
        ErrorLogHelper.log_error(error_message=e, calling_function="EmailHelper.send_email_with_attachments")
        return False

Please advice, thank you.

Rent Charter Buses Company
READ ALSO
Form not processing when passing datas to ajax [duplicate]

Form not processing when passing datas to ajax [duplicate]

This question already has an answer here:

266
Trigger input change on website using Angular with Chrome Extension content script

Trigger input change on website using Angular with Chrome Extension content script

I'm creating a content-script which will populate https://wwwmoneysupermarket

370
posting data to an api [on hold]

posting data to an api [on hold]

So I have 2 entities, Invoice and InvoiceItemI have RestApi for InvoiceItem

257