从下拉菜单中获取选定的值Django

时间:2018-12-24 16:42:23

标签: html django drop-down-menu django-views

我目前有一个下拉菜单,我想从中获取用户选择的元素。 如何将元素返回到views.py?

我希望保持相同的视觉效果,但是我可以使用可以帮助我的任何形式的表单,选项,选择。

   <div id="tableDiv" class="dropdown">
        <button id="tableButton" class="btn btn-sm btn-outline-secondary dropdown-toggle"  type="button"
          data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                   Rank
         <span class="caret"></span>
         </button>
         <ul id="tableMenu" class="dropdown-menu"  aria-labelledby="dropdownMenuLink">
                                <li><a class="dropdown-item" href="#">Att1</a></li>
                                <li><a class="dropdown-item" href="#">Att2</a></li>
                                <li><a class="dropdown-item" href="#">Att3</a></li>
         </ul>
    </div>

谢谢

1 个答案:

答案 0 :(得分:0)

模板:dropdown_menu_form.html

<form action="{% url 'dropdown_menu_form' %}" id="dropdown_menu_form">
<select name="dropdown_menu_option" form="dropdown_menu_form">
  <option value="Att1">Att1</option>
  <option value="Att2">Att2</option>
  <option value="Att3">Ope3</option>
</select>
</form>

urls.py

path('dropdown_menu_form/', views.dropdown_menu_form, name='dropdown_menu_form')

views.py

def dropdown_menu_form(request):
 if request.method == "POST":
  selected_value = request.POST.get('dropdown_menu_option')
  #do something
 else :
  template = 'app_name/dropdown_menu_form.html'
  return render(request, template)