Я хочу створити файл і пов'язати його з FileField
моєї моделі. Ось моя спрощена спроба:
#instantiate my form with the POST data
form = CSSForm(request.POST)
#generate a css object from a ModelForm
css = form.save(commit=False)
#generate some css:
css_string = "body {color: #a9f;}"
#create a css file:
filename = "myfile.css"
#try to write the file and associate it with the model
with open(filename, "wb") as f:
df = File(f) #create django File object
df.write(css_string)
css.css_file = df
css.save()
Заклик до save()
кидає а "seek of closed file"
виняток. Якщо я переміщу save()
до with
блоку, він видає непідтримувану операцію "read"
. На даний момент файли створюються в моєму медіа-каталозі, але порожні. Якщо я просто надам css_string
з HttpResponse
тоді я бачу очікуваний css.
Документи здається, у мене немає прикладу, як зв'язати згенерований файл та поле бази даних. Як це зробити?
Відповіді:
1 для відповіді № 1Джанго FileField
або буде a django.core.files.File
, який є екземпляром файлу або django.core.files.base.ContentFile
, який приймає рядок як параметр і складає a ContentFile
. Оскільки вміст файлу у вас вже був у вигляді рядка, це звучить як ContentFile
це шлях (я не зміг перевірити це, але це має працювати):
from django.core.files.base import ContentFile
# create an in memory instance
css = form.save(commit=False)
# file content as string
css_string = "body {color: #a9f;}"
# create ContentFile instance
css_file = ContentFile(css_string)
# assign the file to the FileField
css.css_file.save("myfile.css", css_file)
css.save()
Перевірте django doc про Деталі FileField.