我有两个下拉菜单,我想检索其值以将它们用作变量来过滤从内部 Web API 检索到的数据。
Views.py
# I want to retrieve the year and week number, so I can use them as values in my filter
def filter():
filters = {"filter": {
"filters": [{
"field": "DateTime",
"operator": "gte",
"value": "2017-07-23 23:59:59"
}, {
"field": "DateTime",
"operator": "lte",
"value": "2017-08-18 23:59:59"
}],
"logic": "and"
}}
我没有使用 Django 表单,因为除了年份之外我没有保存任何其他数据,并且我正在生成周数,但是,如果您认为使用 Django 表单来促进数据处理可能有用,那么可以写从你的 Angular 来看,我想让这个网络应用程序变得更好。
header.html
<form method="POST"> {% csrf_token %}
<h6>Select year</h6>
<select name="select_year">
<option value = "2016" >2016</option>
<option value = "2017"> 2017</option>
<option value = "2018"> 2018</option>
</select>
<h6>Select week</h6>
<select name="select_week">
<!--range is not supported: the spaces represent the number of weeks -->
{% for week in " " %}
<option value="{{forloop.counter}}">{{forloop.counter}}</option>
{% endfor %}
</select>
<button type="submit">Search</button>
</form>
警告:我担心生成周数的代码完全不正确,因为它不是正确的解决方案,并且我已阅读以下帖子 Numeric loops in Django templates , Iterate number in for loops但这已经超出了主题,我的首要任务是获取这两个下拉菜单的值。
最佳答案
解决方案:
def your_view(request):
if request.method == 'POST':
year = request.POST.get('select_year', None)
week = request.POST.get('select_week', None)
# rest of the code
向 html 模板中的 form
添加一个操作,并在 Django 中为其添加一个 urlpattern
,该操作由 your_view
方法处理。
request
对象将数据存储在 POST
字典中,键基于 html 标签 names
。
然后,您可以将这些值传递给您的 filter
方法,以根据需要设置过滤器的格式。
注意:使用 Django Forms 可能更好因为它节省了编写 HTML 代码的时间并清理了值。
引用号:https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.POST
关于javascript - 如何读取Django中下拉菜单的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45743807/