Search code examples
pythondjangodjango-modelsdjango-formsdjango-uploads

How to convert text from TextArea to file?


I have a form where User can fill either text to translate or attach a file. If the text to translate has been filled, I want to create a txt file from it so it seems like User uploaded a txt file.

    if job_creation_form.is_valid():
            cleaned_data_job_creation_form = job_creation_form.cleaned_data
            try:
                with transaction.atomic():
                        text = cleaned_data_job_creation_form.get('text_to_translate')
                        if text:
                           cleaned_data_job_creation_form['file']=create_txt_file(text)

                        Job.objects.create(
                                customer=request.user,
                                text_to_translate=cleaned_data_job_creation_form['text_to_translate'],
                                file=cleaned_data_job_creation_form['file']....
                                )
            except Exception as e:
                RaiseHttp404(request, 'Something went wrong :(')
            return HttpResponseRedirect(reverse('review_orders'))

I though about creating a txt file like:

with open('name.txt','a') as f:
    ...

But there can be many problems - the directory where the file is saved, the name of the file which uploading handles automatically etc.

Do you know a better way?

In short:

If the text to translate has been filled, fake it so it looks like txt file has been uploaded.


Solution

  • use a tempfile maybe?

    import tempfile
    tmp = tempfile.TemporaryFile()
    tmp.write("Hello World!\n")
    Job.objects.create(file=File(tmp),...)
    

    Hope this helps