E
E
Egor2018-10-01 15:54:08
Django
Egor, 2018-10-01 15:54:08

How to take a file from a Django project folder and add it to a model?

There is a file generated by the python-docx library. I saved it as: Now I want to add it to the field of the model object:
document.save(my_doc_name + '.doc')

f = open(settings.BASE_DIR+'\\'+my_doc_name + '.doc', 'rb')

today = datetime.now().date()

mydoc = Document(name=my_doc_name, file=f, data=today)
mydoc.save()

Thus, it didn't work out. The path seems to be correct.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pasechnik Kuzmich, 2018-10-03
@Hivemaster

from django.core.files.base import ContentFile

with open(os.path.join(settings.BASE_DIR. my_doc_name + '.doc'), 'rb') as f:
    mydoc.file.save(my_doc_name, ContentFile(f.read()))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question