【问题标题】:Value of Select Option in Django's Views.pyDjango 的 Views.py 中 Select 选项的值
【发布时间】:2019-09-26 11:01:02
【问题描述】:

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

【问题讨论】:

  • 您是否尝试从您的 views.py 中 POST 的下拉列表中访问值?
  • 我已经改成 GET
  • 好的,所以在你的 views.py 中你想在这里做什么,results = Results.objects,如果你想查询模型,请查看这里的文档 (docs.djangoproject.com/en/2.2/topics/db/queries/…),查询你写的似乎不完整。
  • 我想获取select标签内选择的选项的值
  • 如果您想在视图中获取所选选项的值,然后更改视图内的逻辑,请参阅我的答案。

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


【解决方案1】:

所以要在视图中获取表单值,你必须像form_val = request.GET.get('field_name', &lt;default_value&gt;)那样做,所以在代码中添加几行

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}

【讨论】:

  • 很高兴听到这个消息,请接受这个答案,这样如果有人提到这个答案,他们可以确定它是正确的
  • 我试过了,它也有效:def allresults(request): results = Results.objects.all() mon = request.POST['mahina'] yea = int(request.POST['saal']) pdf_url = {} ti = [] da = [] for i in results: m = i.month y = i.year f = i.file u = f.url t = i.title d = i.date
猜你喜欢
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多