我尝试在textarea
中显示文本(.txt)文件的内容,并在编辑后保存。
如何正确保存编辑过的文件?
模型:
class FileDb(models.Model):
source = models.FileField(upload_to="source")
的观点:
def single_file(request,id):
file = FileDb.objects.get(id=id)
filename = file.source.read()
#save edited file:
if request.method == "POST":
content = request.POST['content']
file.source = content
file.save()
return render_to_response('single_file.html',{'file':file,'filename':filename},context_instance=RequestContext(request))
模板:
<form method="POST">{% csrf_token %}
<textarea name="content">{{filename}}</textarea>
<input type="submit" value="Save changes">
</form>
答案 0 :(得分:3)
您只是不会将string
分配给FileField
file.source = content
您必须将内容写入文件,如下所示:
if request.method == "POST":
from django.core.files import File
f = open(file.source.path, 'w')
content = request.POST['content']
f.write(content)
f = File(f)
file.source = f
file.save()
希望这有帮助!