gpt4 book ai didi

python - Django 。如何编辑并保存 json 文件中的更改?

转载 作者:行者123 更新时间:2023-12-01 04:55:36 25 4
gpt4 key购买 nike

我尝试编辑 .json 文件并保存它。我不知道如何编写其余代码。模型.py

class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
pubdate = models.DateTimeField(default=datetime.now, blank=True)

编辑.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)

一切正常。

最佳答案

在您的示例中,您已对保存的 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,因为你在原文中写道)。对使用 w 打开的文件调用 read 将导致 Python 2 中的 IOError 异常和 io.UnsupportedOperation 异常Python 3。

关于python - Django 。如何编辑并保存 json 文件中的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27462560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com