django - Django:获取点击按钮的ID
问题描述
我正在使用 django。在我看来,我想知道按下了哪个按钮。
我的template.html看起来像:
{% for post in posts %}
<button name="{{ post.pk }}" type="submit">{{ post.title }}</button>
{% endfor %}
我知道在我的views.py中我可以检查按钮x是否被按下:
if '12345' in request.POST:
# do something
elif '23456' in request.POST:
#do something else
但是有没有办法在不检查每个可能的键的情况下获取主键?
我会喜欢这样的东西:
#PSEUDOCODE
post_primary_key = request.POST.get_name()
如果我的方法从根本上说不好,我也愿意接受其他解决问题的方法。
解决方案
在你的 template.html
{% for post in posts %}
<a href="{% url 'url_name_which directs_to_your_view' pk=post.pk %}">{{ post.title }}</a>
{% endfor %}
在你的意见.py
def your_view(request, pk):
# pk is your primary key, do whatever you want no need to check manually
在 urls.py
path('post/<int:pk>/', views.your_view, name='url_name_which directs_to_your_view'),
推荐阅读
- python - 有没有更简单的方法来执行和分组矩阵求和?
- javascript - Node.js async.mapSeries 用于具有 2000 个对象数组的 JSON
- css - 父元素下方的伪元素
- ios - 如何在用户关闭模式之前显示 ActionSheet
- python - 如何在 Python 中创建 JSON 类或从示例数据构造
- python - 在python中没有初始点击就播放声音
- python - 试图控制我的 Pong 循环速度
- asp.net-mvc - 参数“inArray”即将为空。为什么?
- javascript - 如何使用 Moment 解析没有偏移的时间字符串?
- arrays - 以最好的顺序和最快的时间找到一个特殊数组的峰值