gpt4 book ai didi

django - Django 的 Views.py 中选择选项的值

转载 作者:行者123 更新时间:2023-12-05 04:00:38 25 4
gpt4 key购买 nike

我在模板中使用 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>

这是我的views.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}

最佳答案

所以要在 View 中获取表单值,你必须像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}

关于django - Django 的 Views.py 中选择选项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com