0
我嘗試編輯.json文件並保存。 我不知道如何編寫代碼的其餘部分。 models.pyDjango。如何編輯和保存json文件中的更改?
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 - EDITED - 正常工作:
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)
一切工作正常。
使用您的代碼我在關閉的文件上獲得ValueError I/O操作。 – bartekch 2014-12-13 23:13:10
@bartekch我提供的代碼片段需要在'with'語句中縮進。 (在這種情況下'with'的結論會自動關閉該文件。) – 2014-12-13 23:21:39
現在我明白了'with'語句的工作原理:) Thanx。我編輯問題,edit()函數工作正常。 – bartekch 2014-12-14 14:09:10