0

I've been struggling to solve this myself for a good while now and I just can't understand how it works. I found a way to get my generated file straight into the model, but it doesn't serve its purpose well because I also need the file to be uploaded to Amazon Web Services. Any solution that helps me with this is appreciated! In my code, I request a JSON file from the user and generate a text file in a specific format using it. This needs to both make its way to the field in the model, and be uploaded to the storage system in AWS. Here's my view as it is currently:

def sped_create(request):
form = SpedForm(request.POST, request.FILES, None)
# sped = get_object_or_404(Sped, pk=id)

if form.is_valid():
    data = json.load(form.cleaned_data['json_file'].open())
    # (json is successfully processed here: I've confirmed that the lines that would usually be here are irrelevant to the problem)
    f_txt = open(f"static/file_created_txt/bacon.txt", "w+", encoding='utf-8')  # FALTA ARRUMAR O DIRETÓRIO
    for string in fileTxt:
        f_txt.write(f"{string}\n")
    f_txt.close()
    instance = SpedForm(sped_file=request.FILES['static/file_created_txt/bacon.txt'])
    instance.save()
    sped = form.save()
    return redirect(sped_list)

return render(request, 'sped_form.html', {'form': form})

Currently, I've been getting this traceback:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/sped_create/

Django Version: 2.2.7
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'materialize',
 'storages',
 'widget_tweaks',
 'core',
 'boto']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\Luís Gustavo\Desktop\Sped\.venv\lib\site-packages\django\utils\datastructures.py" in __getitem__
  78.             list_ = super().__getitem__(key)

During handling of the above exception ('static/file_created_txt/bacon.txt'), another exception occurred:

File "C:\Users\Luís Gustavo\Desktop\Sped\.venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Luís Gustavo\Desktop\Sped\.venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Luís Gustavo\Desktop\Sped\.venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Luís Gustavo\Desktop\Sped\.venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "C:\Users\Luís Gustavo\Desktop\Sped\core\views\sped.py" in sped_create
  66.         instance = SpedForm(sped_file=request.FILES['static/file_created_txt/bacon.txt'])

File "C:\Users\Luís Gustavo\Desktop\Sped\.venv\lib\site-packages\django\utils\datastructures.py" in __getitem__
  80.             raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /sped_create/
Exception Value: 'static/file_created_txt/bacon.txt'
Luisffx
  • 13
  • 5
  • first, where is defined `fileTxt`, f_txt.write, should recive bytes not str, then the problem `request.FILES` does not have a key `static/file_created_txt/bacon.txt`, also use request.FILES.get instead of index, then to associate a file created by you try with this: https://stackoverflow.com/questions/3501588/how-to-assign-a-local-file-to-the-filefield-in-django#answer-3502356 – juancarlos Dec 04 '19 at 14:51
  • Could you please explain how I'd pass bytes and also show an example on how to use request.FILES.get? I assume regarding the bytes that I'd have to say f_txt.write(string + "\n") , is that right? – Luisffx Dec 04 '19 at 15:01
  • reques.FILES does not have a key `static/file_created_txt/bacon.txt` then it raise `MultiValueDictKeyError` with ``request.FILES.get('static/file_created_txt/bacon.txt')` if key does not exists not raise that exception, but it not solve your problem, i think you should after write content is writted in f_txt reopen in read mode and pass it to `SpeedForm(speed_file=f_txt)` or some like this – juancarlos Dec 04 '19 at 15:22
  • That doesn't work. sped_file isn't an argument that the form accepts. – Luisffx Dec 04 '19 at 16:58
  • but if you have passed that argument `instance = SpedForm(sped_file=request.FILES['static/file_created_txt/bacon.txt'])` – juancarlos Dec 04 '19 at 17:11

0 Answers0