我在Django程序中遇到了一个有趣的障碍。我正在尝试创建一个小型日历程序,用户可以在其中查看df_pop_county$color <- rainbow(n = 50, y / max(y))
中的日历,并使用所需的内容对其进行更新,它将把更新推送到日历中,并且您将能够从中看到更新的日历。任何地方。我尝试使用文件存储日历信息,但是遇到了文件无法更新等问题。
因此,我采用了一种新方法,改为将日历存储在全局变量中,并将信息传递到程序中需要的任何地方。
这是程序:
views.py
textarea
forms.py
from django.shortcuts import render
from django.contrib import messages
import sys
global file_content
f = open('calendar.txt', "r")
file_content = f.read()
f.close()
if f.closed:
print("CLOSED FILE from read views")
def writeFile(content, file):
from .forms import FileForm
f = open(file, "w")
f.write(content)
f.close()
if f.closed:
print("CLOSED FILE from write views")
def home(request):
from .forms import FileForm
return render(request, 'main/index.html',{'file_content':file_content})
def form_get(request):
from .forms import FileForm
if request.method == 'POST':
# 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():
global file_content
cd = form.cleaned_data['form']
writeFile(cd, 'calendar.txt')
file_content = cd
print(file_content)
else:
form = FileForm()
return render(request, 'main/index.html', {'form': form})
def thanks(request):
from .forms import FileForm
if request.method == 'POST':
# 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():
global file_content
cd = form.cleaned_data['form']
writeFile(cd, 'calendar.txt')
file_content = cd
print(file_content)
else:
form = FileForm()
return render(request, 'main/index.html', {'form': form})
您可能会说,在from django import forms
global cd
from .views import file_content
content = file_content
def getContent():
global file_content
from .views import file_content
content = file_content
print(content + "FROM FORMS")
class FileForm(forms.Form):
getContent()
form = forms.CharField(label='',initial=content,widget=forms.Textarea(attrs={'width':"100%", 'cols' : "102", 'rows': "40", }))
中处理文本区域中的表单内容,然后views.py
将其导入。问题是,这仅在启动时起作用,并且每次更新表单以显示新内容时,类forms.py
都不会收到信息。本质上,它“更新”的唯一方法是当我更改代码中的某些内容时,Django自动执行系统检查。我无法找到一种有效的方法来使FileForm
意识到日历中已有更新。有什么办法吗?