这是我的模板:
<form action="{% url "calculate" %}>
<label2>
<select name="ASSETS_filn">
<option selected>Files</option>
{% for document in documents %}
<option>{{ document.filename }}</option>
{% endfor %}
</select>
</label2>
<br>
<label>Date</label>
<input class="button3" type="text" name="DATE_val" />
<input class="button3" type="submit" value="Calculate" />
</form>
label2是一个下拉菜单。我的目标是:让用户从下拉菜单中选择一个项目,并在日期框中输入数据。这是处理此问题的视图:
def calculate(request):
os.chdir(settings.PROJECT_PATH + '/calc/')
f = open('calc_log.txt', 'w') # Could change to 'a' for user activity log
f.write("hehehehe")
for key in request.POST:
f.write(str(key) + " " + str(request.POST[key]) + '\n')
f.write('\n\n')
f.write("test")
f.close()
return render( #...
但写入.txt
文件的所有内容都是hehe
和test
。 request.POST
是空的吗?
答案 0 :(得分:2)
By default, the method of form submit is GET
,您打算进行POST
。
因此,请指定方法:
<form action="{% url 'calculate' %}" method="POST">
另外,检查方法是个好主意:
def calculate(request):
if request.method == "POST":
os.chdir(settings.PROJECT_PATH + '/calc/')
f = open('calc_log.txt', 'w') # Could change to 'a' for user activity log
f.write("hehehehe")
for key in request.POST:
f.write(str(key) + " " + str(request.POST[key]) + '\n')
f.write('\n\n')
f.write("test")
f.close()
#...