首页 > 解决方案 > 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}

标签: djangodjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


所以要在视图中获取表单值,你必须这样做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}

推荐阅读