我尝试编辑.json文件并保存。 我不知道如何编写其余的代码。 models.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
pubdate = models.DateTimeField(default=datetime.now, blank=True)
edit.html
{% for key, value in mydata.items %}
<form method="POST">{% csrf_token %}
<textarea name="content">{{value}}</textarea>
<input type="submit" value="Zapisz">
</form>
{% endfor %}
views.py - 已编辑 - 工作正常:
def edit(request, document_id=1):
with open('/home/path/to/files/'+str(Document.objects.get(id=document_id).docfile.name), 'r+') as json_file:
mydata = json.loads(json_file.read())
if request.method == 'POST':
for key in mydata:
mydata[key] = request.POST.get('content', '')
# Move the position to the begnning of the file
json_file.seek(0)
# Write object as JSON
json_file.write(json.dumps(mydata))
# Truncate excess file contents
json_file.truncate()
args = {}
args['mydata'] = mydata
args.update(csrf(request))
return HttpResponseRedirect('/specific_document/%s' % document_id, args)
else:
with open('/home/path/to/files/'+str(Document.objects.get(id=document_id).docfile.name), 'r') as json_file:
mydata = json.loads(json_file.read())
args = {}
args['mydata'] = mydata
args.update(csrf(request))
return render_to_response('edit.html', args)
一切正常。
答案 0 :(得分:2)
在您的示例中,您已对保存的JSON文件进行反序列化,因此mydata
是一个Python对象。您可以像修改任何其他Python对象一样对其进行修改。
例如,要将textarea
的内容添加为字典键:
if request.method == 'POST':
mydata['content'] = request.POST.get('content', '')
# Move the position to the begnning of the file
json_file.seek(0)
# Write object as JSON
json_file.write(json.dumps(mydata))
# Truncate excess file contents
json_file.truncate()
注意:如果您同时阅读和编写文件的内容,mode
参数应为r+
(而不是w
,正如您在原文中所写的那样)。在使用read
打开的文件上调用w
将导致Python 2中出现IOError
异常,Python 3中出现io.UnsupportedOperation
异常。