Django的Views.py中Select Option的值

时间:2019-05-08 16:38:12

标签: django django-models django-forms django-templates django-views

我正在模板中使用选择标签以及在表单标签内具有“提交”类型的链接。当我从下拉菜单中选择一个选项并单击按钮时,它会转到下一页,但是我无法获取所选选项的值。其显示的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}

1 个答案:

答案 0 :(得分:1)

因此,要在视图中获取表单值,您必须像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}