我在这里问了几个与我正在处理的Django项目有关的问题,该项目在表单中显示文件的内容,提交后,您可以使用该表单编辑文件,项目会写入文件并且更改会自动反映出来。
因此,我已经获得了一个项目,用于在表单中显示日历文本文件的内容,并且已经能够将表单内容放入我的Python脚本中进行操作。我遇到的问题是将该内容写入文件,因为由于某种原因,更改直到我重新启动服务器后才提交(这并不理想,因为它应该能够连续运行)。
我怀疑这与文件“关闭”后由于某种原因仍保持打开状态有关。我试图通过为所有读取和写入操作(也将关闭文件)创建函数来解决此问题,以便每次需要读取/写入时都可以调用它们。问题仍然存在。我在这里做错了什么吗?文件仍在我找不到的地方打开吗?下面的资源。
链接到项目: https://repl.it/@xMikee/Calendar(日历只是暂时的模板)
views.py
from django.shortcuts import render
from django.contrib import messages
from .forms import FileForm
import sys
f = open('calendar.txt', "r")
file_content = f.read()
f.close()
if f.closed:
print("CLOSED FILE from read views")
def writeFile(content, file):
f = open(file, "w")
f.write(content)
f.close()
if f.closed:
print("CLOSED FILE from write views")
def home(request):
return render(request, 'main/index.html',{'file_content':file_content})
def form_get(request):
print('got form')
if request.method == 'POST':
print("OK")
# create a form instance and populate it with data from the request:
form = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
print("OK")
cd = form.cleaned_data['form']
writeFile(cd, 'calendar.txt')
else:
print('NOT OK')
form = FileForm()
return render(request, 'main/index.html', {'form': form})
def thanks(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
print("OK")
# create a form instance and populate it with data from the request:
form = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
print("OK")
cd = form.cleaned_data['form']
print(cd)
f = open('calendar.txt', 'r+')
f.write(cd)
f.close()
else:
print('NO POST')
form = FileForm()
return render(request, 'main/index.html', {'form': form})
forms.py
from django import forms
global cd
f = open('calendar.txt', "r")
file_content = f.read()
f.close()
if f.closed:
print("CLOSED FILE from read views")
class FileForm(forms.Form):
form = forms.CharField(label='',initial=file_content,widget=forms.Textarea(attrs={'width':"100%", 'cols' : "102", 'rows': "40", }))
index.html
{% extends "base.html" %}
{% block content %}
<h1 style='text-align:center'>Welcome to the calendar!</h1>
<div style='text-align:center'>
<form action="#" method="post">
{% csrf_token %}
{{ form }}
<div style='margin: 0 auto'>
<input type="submit" value="Submit">
</div>
</form>
<p>{{cd}}</p>
</div>
{% endblock content %}