我将以我是python初学者为开头。
我正在尝试构建一个非常简单的应用程序,用户可以在其中上传ics文件,并在提交后对该文件进行解析,并且该应用程序以清晰的格式显示内容。
我正在尝试使用FileSystemStorage(),但似乎无法正确设置它。
这是我的views.py和模板的外观。
# views.py
from django.core.files.storage import FileSystemStorage
from django.views.decorators.clickjacking import xframe_options_exempt
from icalendar import Calendar, Event
from pytz import UTC
@xframe_options_exempt
def index(request):
if request.method == 'POST' and request.FILES['icsfile']:
myfile = request.FILES['icsfile']
fs = FileSystemStorage()
filename = fs.save(icsfile.name, icsfile)
uploaded_file_url = fs.url(filename)
g = open(uploaded_file_url, 'rb')
gcal = Calendar.from_ical(g.read())
for component in gcal.walk():
if component.name == "VEVENT":
summary = component.get('summary')
description = component.get('description')
start_time = component.get('dtstart')
end_time = component.get('dtend')
g.close()
return render(request, 'ics_parser/index.html', {
'uploaded_file_url': uploaded_file_url,
'summary': summary,
'description': description,
'dtstart': dtstart,
'dtend': dtend,
})
return render(request, 'ics_parser/index.html', {})
# index.html
<div class="ics-formatter"></div>
<div class="row">
<div class="col-sm-6">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="icsfile">
<button type="submit">Upload</button>
</form>
</div>
<div class="col-sm-6">
{% if uploaded_file_url %}
<p>{{description}}</p>
{% endif %}
</div>
</div>
这是我得到的错误:
异常类型:NameError
异常值:
名称“ icsfile”未定义
答案 0 :(得分:0)
您将文件定义为myfile
尝试更换
filename = fs.save(icsfile.name, icsfile)
使用
filename = fs.save(myfile.name, icsfile)