2014-12-13 49 views
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) 

一切工作正常。

回答

1

在你的例子中,你已經反序列化了保存的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異常和Python 3中的io.UnsupportedOperation異常。

+0

使用您的代碼我在關閉的文件上獲得ValueError I/O操作。 – bartekch 2014-12-13 23:13:10

+0

@bartekch我提供的代碼片段需要在'with'語句中縮進。 (在這種情況下'with'的結論會自動關閉該文件。) – 2014-12-13 23:21:39

+0

現在我明白了'with'語句的工作原理:) Thanx。我編輯問題,edit()函數工作正常。 – bartekch 2014-12-14 14:09:10

相關問題