3

我尝试在其中显示文本(.txt)文件的内容textarea并在编辑时保存它。

如何正确保存编辑的文件?

楷模:

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>
4

1 回答 1

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()

希望这可以帮助!

于 2013-05-24T13:43:30.587 回答