首页 > 解决方案 > 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()

如果我的方法从根本上说不好,我也愿意接受其他解决问题的方法。

标签: djangobuttonrequest

解决方案


在你的 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'),

推荐阅读