0

I am using django 1.8 and python 3.4 and trying to create a json file and then writing into it, after that I need to save it to my database but on save it returns me an error '_io.TextIOWrapper' object has no attribute '_committed'. Can anyone please help where I am doing wrong? Here is my models.py

class ConvertedFile(models.Model):
    file = models.FileField(upload_to='json/upload', max_length=5000)
    created_on = models.DateTimeField(auto_now_add=True)

My views.py is-

def convert_file(request):
    url = request.GET.get('q', None)
    r = requests.get(url, stream=True)
    with open('file.csv', 'wb') as out_file:
        shutil.copyfileobj(r.raw, out_file)
    csvfile = open("file.csv", "r")
    jsonfile = open("file.json", "w")
    csv_rows = []
    reader = csv.DictReader(csvfile)
    title = reader.fieldnames
    try:
        for row in reader:
            csv_rows.extend([{title[i]: row[title[i]] for i in range(len(title))}])
    except:
        pass

    jsonfile.write(json.dumps(csv_rows, sort_keys=False, indent=4, separators=(',', ': '), ensure_ascii=False))

    os.remove("file.csv")
    jsonfile.close()

    new_json = ConvertedFile.objects.create()
    new_json.file = jsonfile
    new_jsone.save()
Karan
  • 3
  • 2

1 Answers1

0

The error raises on model.save() in the last line, right? The line above new_json.file = jsonfile is the problem. You pass the reference to a closed (plain python) file object to the FileField from django and it does not know how to deal with it (_commited is missing for example).

Have a look at Django - how to create a file and save it to a model's FileField?

Community
  • 1
  • 1
dahrens
  • 3,879
  • 1
  • 20
  • 38