我在家庭视图中提交表单后,我们会被重定向到我的下载视图,该视图对我的会话变量有错误的响应...为什么???我不确定如何解决这个问题,感觉就像我已经尝试过一切。
@login_required
def Home(request):
form = TimeForm()
search_times = []
if request.method == "POST":
# clear session data
# for key in request.session.keys():
# test.append(request.session[key])
start = request.POST['start_time']
end = request.POST['end_time']
start = time.mktime(datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S").timetuple())
end = time.mktime(datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S").timetuple())
start = re.split('.[0-9]+$', str(start))[0]
end = re.split('.[0-9]+$', str(end))[0]
search_times.append(int(start))
search_times.append(int(end))
request.session['search_times'] = search_times
request.session.save()
context = {
'form': form,
'search_times': search_times,
}
return render(request, "pcap_app/home.html", context)
def Download(request, path):
test = []
access_time = []
search_times = []
search_times = request.session.get('search_times', False)
# testing timestamp directory listing
files = sorted_ls(os.path.join(settings.MEDIA_ROOT, path))
for f in files:
time = os.stat(os.path.join(settings.MEDIA_ROOT, f)).st_mtime
access_time.append(int(re.split('.[0-9]+$', str(time))[0]))
context = {
'sort': files,
'times': access_time,
'search': search_times,
'test': test,
}
return render(request, "pcap_app/downloads.html", context)
home.html的
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet" type="text/css"/>
<script src="{{ STATIC_URL }}js/bootstrap.js"></script>
{{ form.media }}
</head>
<body>
<h1>pcap search</h1>
{% if user.is_authenticated %}
<form action="/download/" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input id="submit" type="submit" value="Submit">
</form>
{{ search_times }}
{{ test }}
<a href="/logout/">Logout</a>
{% else %}
<a href="/login/?next={{ request.path }}">Login</a>
{% endif %}
</body>
答案 0 :(得分:2)
尝试保存会话
request.session.save()
答案 1 :(得分:1)
您错误地将action
模板中的home.html
属性设置为/download/
。
提交表单时,POST
请求已提交到/download/
视图,而不是home
视图。因此,永远不会执行设置会话的代码。
您需要将action
属性更改为home
视图网址。执行此操作时,如果发出POST
个请求,则会在会话中设置变量search_times
。
<form action="/home/url/" method="POST">
在action
中指定home.html
属性后,您需要在/download/
视图中重定向到home
。然后,在您的download
视图重定向后,您将在会话中访问search_times
vaiable。
@login_required
def Home(request):
form = TimeForm()
search_times = []
if request.method == "POST":
...
request.session['search_times'] = search_times # set the variable in the session
return HttpResponseRedirect('/download/') # redirect to download page
context = {
'form': form,
'search_times': search_times,
}
return render(request, "pcap_app/home.html", context)