Как я могу отправить файл, созданный javascript, на сервер, а затем обработать его с помощью django для отправки по электронной почте? - PullRequest
0 голосов
/ 14 ноября 2018

Мой код JavaScript:

function PrepareEmailPrescription() {
    doc = PreparePrescriptionPDF()
    var pdf = doc.output();   
    var fd = new FormData();    
    fd.append( 'file', pdf );
    $.ajax({
        url: `/clinic/${cliniclabel}/prescription/sendemail/patient/${patient_id}`,
        data: fd,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
        alert(data);
        }
    });  
}

Здесь PreparePrescriptionPDF - это функция, которая генерирует файл PDF с pdfjs.

На сервере django у меня есть:

def SendPrescriptionbyMail(request, cliniclabel, patient_id):
    # print(request.body)
    print(request.FILES)
    print(request.FILES['file'])
    return HttpResponse('Successfully sent email')

Я получаю следующий ответ от django:

[14/Nov/2018 15:59:18] "GET /clinic/medicines HTTP/1.1" 200 8389
<MultiValueDict: {}>
2018-11-14 15:59:22,344 django.request ERROR    Internal Server Error: /clinic/madhav/prescription/sendemail/patient/18
Traceback (most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/utils/datastructures.py", line 77, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/myappointments/clinic/views.py", line 4911, in SendPrescriptionbyMail
    print(request.FILES['file'])
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/utils/datastructures.py", line 79, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'file'

Однако, если мой код JavaScript становится:

function PrepareEmailPrescription() {
    doc = PreparePrescriptionPDF()
    var pdf = new Blob(['abc123'], {type: 'text/plain'});
    var fd = new FormData();    
    fd.append( 'file', pdf );
    $.ajax({
        url: `/clinic/${cliniclabel}/prescription/sendemail/patient/${patient_id}`,
        data: fd,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
        alert(data);
        }
    });  
}

Я получаю:

[14/Nov/2018 15:57:05] "GET /clinic/medicines HTTP/1.1" 200 8389
<MultiValueDict: {'file': [<InMemoryUploadedFile: blob (text/plain)>]}>
2018-11-14 15:57:10,500 django.request ERROR    Internal Server Error: /clinic/madhav/prescription/sendemail/patient/18
Traceback (most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 93, in __call__
    response = self.process_response(request, response)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/middleware/common.py", line 105, in process_response
    if response.status_code == 404:
AttributeError: 'str' object has no attribute 'status_code'

Как правильно это сделать? Как я могу отправить созданный на лету файл PDF на мой сервер django для отправки по электронной почте в виде вложения?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...