变量“名称”以 django 模板形式
我有以下模板,其中同时具有“添加”和“删除”按钮:
<tr>
<td>Position</td>
<td>{{ form.position }}<input type="submit" value="add" , name='add'/></td>
</tr>
<tr>
<td> </td>
<td>
{% for position in positions %}
{{ position}}<input type="submit" value="Delete", name="delete-position.{{ position }}"/>
{% endfor %}
</td>
</tr>
如何构造views.py 函数来查找删除提交按钮的name
值?我目前有:
try:
request.POST['add']
positions.append(request.POST['position'])
return render_to_response('registration/getting_started_info1.html', {'form': form, 'positions': positions}, context_instance = RequestContext(request))
except:
if 'delete-position' in request.POST:
positions.remove(### how to get name of Delete submit? ###)
return render_to_response('registration/getting_started_info1.html', {'form': form, 'positions': positions}, context_instance = RequestContext(request))
另外,是否有更好的方法来构造视图/模板,以便我可以使用 if...else
而不是 try... except
?
I have the following template, which has both an "add" and "delete" button:
<tr>
<td>Position</td>
<td>{{ form.position }}<input type="submit" value="add" , name='add'/></td>
</tr>
<tr>
<td> </td>
<td>
{% for position in positions %}
{{ position}}<input type="submit" value="Delete", name="delete-position.{{ position }}"/>
{% endfor %}
</td>
</tr>
How would I construct the views.py function to find the name
value of the Delete submit button? I currently have:
try:
request.POST['add']
positions.append(request.POST['position'])
return render_to_response('registration/getting_started_info1.html', {'form': form, 'positions': positions}, context_instance = RequestContext(request))
except:
if 'delete-position' in request.POST:
positions.remove(### how to get name of Delete submit? ###)
return render_to_response('registration/getting_started_info1.html', {'form': form, 'positions': positions}, context_instance = RequestContext(request))
Also, is there a better way to construct the view/template so I can use an if...else
instead of a try...except
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您可能应该这样做:
这应该对您的要求有所帮助...但是,我不确定这是否是完成您想要做的事情的最简单的方法。
First, you should probably do this:
That should help with what you're asking... however, I'm not sure if it's the easiest method to do what you're trying to do.
保存会话中的位置。
Save the positions in the session.
你的 try-catch 有点奇怪。您可能应该向不同的视图提交删除请求。
但至于如何获取
delete-position
变量,很简单:Your try-catch is kind of weird. You should probably be submitting delete requests to a different view.
But as to how you can get the
delete-position
vars, it's easy: