Django一个表单对应多个按钮解决方案
需求:
在django中,有时候我们需要在一个表单中设置多个按钮实现不同的功能。
解决方法:
为不同按钮添加不同name属性,然后再后台判断name值。例如:
<form class="form-horizontal" role="form" method="POST" action="{% url 'choose_paper:setPaper' %}">
{% csrf_token %}
<div class="form-group">
<div class="col-sm-2 col-lg-offset-1">
<p>年份</p>
<input type="text" id="date" name="datetimepicker" value=" "
placeholder="选择年份" class="form-control">
</div>
<div class="col-sm-2 col-lg-offset-1">
<p>会议</p>
<div class="form-group">
<input type="text" name="venue" class="form-control">
</div>
</div>
</div>
<div class="col-sm-offset-2 col-sm-3">
<button type="button submit" class="btn btn-info btn-lg btn-block" name="paper_set">
详情</button>
</div>
然后通过不同的name实现不同功能
def function(request): # 根据会议和年份筛选数据集合
if request.POST:
if 'paper_set' in request.POST:
year = request.POST['datetimepicker']
venue = request.POST['venue']
context = {
'year': year,
'venue': venue
}
else:
context={
'year': "",
'venue': ""
}
return render(request, 'choose_paper/setpaper.html', context)
参考:
https://blog.csdn.net/destinymf/article/details/81135131
数据处理(论文id/论文year/论文venue 形式):
代码:
#用来生成id year venue 文件
with open('./articles.txt', 'r', encoding='utf-8') as f1:
with open('./years.txt', 'r', encoding='utf-8') as f2:
with open('./venues.txt', 'r', encoding="ISO-8859-1") as f3:
ids=f1.readlines()
years=f2.readlines()
venues=f3.readlines()
with open('./id_year_venue.txt', 'a', encoding='utf-8') as f4:
for i in range(len(ids)):
f4.write(ids[i])
f4.write(years[i])
f4.write(venues[i])
f4.write("\n")
获取满足条件的(年份&会议)的论文集合(id):
简单的输出:
代码:
if 'paper_set' in request.POST:
year = request.POST['datetimepicker']
venue = request.POST['venue']
articals=""
with open("choose_paper/data/id_year_venue.txt",'r',encoding='utf-8') as f:
lines=f.readlines()
i=0
while i< len(lines)-3:
a=lines[i].strip()
b=lines[i+1].strip()
c=lines[i+2].strip()
if(b==year and c==venue):
articals+=a
articals+=" "
i+=4
context = {
'articles':articals#获取满足年份,会议的论文id
}