django - Django 的 Views.py 中 Select 选项的值
问题描述
我在模板中使用选择标签以及在表单标签内具有“提交”类型的链接。当我从下拉列表中选择一个选项并单击按钮时,它会转到下一页,但我无法获得所选选项的值。它显示的 AttributeError 'Manager' 对象没有属性 'month'。这是我的代码:
<form method="POST" action="{% url 'results' %}">
{% csrf_token %}
<select name="mahina" id="month">
<option value="all">All</option>
<option value="jan">January</option>
<option value="feb">February</option>
</select>
<a href="{% url 'results' %}" type="submit">Search</a>
</form>
这是我的意见.py
from django.shortcuts import render
from .models import Results
def allresults(request):
results = Results.objects
if request.method == "GET":
month = results.month
year = results.year
return render(request, 'results/allresults.html', {'results': results}
解决方案
所以要在视图中获取表单值,你必须这样做form_val = request.GET.get('field_name', <default_value>)
,所以在代码中添加几行
def allresults(request):
# this will get the value of the selected item, print this to know more
mahina = request.GET.get('mahina', None)
#Just writing the below query field month randomly, since the models isn't posted
results = Results.objects.filter(month=mahina)
# We don't need to give GET since by default it is a get request
# Since there are multiple objects returned, you must iterate over them to access the fields
for r in results:
month = r.month
year = r.year
return render(request, 'results/allresults.html', {'results': results}
推荐阅读
- android - androidx.navigation.NavGraph 无法转换为 androidx.navigation.compose.ComposeNavigator$Destination
- typescript - 如何将自定义属性添加到 axios 配置?
- sql - Laravel Eloquent:在 where 子句中添加变量(未定义的变量)
- html - Angular(primeng)使用 Ctrl + Shift 复制多行
- c# - 在 2 个控制器 ASP.NET Core 3.1 MVC 之间传递 ID
- javascript - 减小 Monthview 上的单元格大小
- vue.js - Vuex - axios Post 给出不同的错误
- mysql - 删除记录mysql
- php - HTML 中日历日期的值在刷新时会丢失
- javascript - Javascript 文档准备就绪未运行