0

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.

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

3

use a tempfile maybe?

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

Hope this helps

pleasedontbelong
  • 19,542
  • 12
  • 53
  • 77
  • Thanks, it works but there is an error when I pass characters like č,ú etc. It returns: Exception Value: 'ascii' codec can't encode character u'\xfa' in position 24: ordinal not in range(128). I tried to tmp.write(unicode(cleaned_data_job_creation_form.get('text_to_translate'))) But it's the same error. – Milano Aug 12 '16 at 08:39
  • 1
    try http://stackoverflow.com/questions/6048085/writing-unicode-text-to-a-text-file – pleasedontbelong Aug 12 '16 at 08:39