python - Django 没有将数据传递给 POST 请求的 View

标签 python jquery html css django

我创建了一个下拉菜单,该菜单应该将数据传递到有助于过滤查询集的 View 。但是,数据似乎并没有真正传递给 View 。下面是我写的相关代码。

模板.html

<!-- Query based content for dropdown menu -->
<form method="POST" action="{% url 'property-selected' %}" id="property-select">
    {% csrf_token %}
    <select class="dropdown-content" onchange="this.form.submit()" name="property-select">
        {% if current_user_meters %}
            <option disabled selected> -- select an option -- </option>
            {% for meter in current_user_meters %}
                <option class="dropdown-menu-option" value="{{meter.id}}">{{meter.name}}</option>
            {% endfor %}
        {% else %}
            <option>You don't have any meters</option>
        {% endif %}
    </select>
</form>

View .py

def property_selected(request):
    if request.method == 'POST':

        selection = request.POST.get('property-select')

        current_user_groups = Group.objects.filter(
            id__in=request.user.groups.all()
        )
        current_user_properties = Property.objects.filter(
            groups__in=current_user_groups
        )
        current_user_meters = Meter.objects.filter(
            meter_id__in=current_user_properties
        )

        selected_meters = Meter.objects.filter(name=selection)
        selected_meter_data = MeterData.objects.filter(
            name=selection
        ).order_by('date')

        return render(request, 'properties/property-selected.html', {
            'current_user_meters': current_user_meters,
            'selection': selection,
            'selectected_meters': selected_meters,
            'selected_meter_data': selected_meter_data,
        })

对于 View 文件中的查询集,selection 变量似乎没有得到任何东西,而这正是我希望来自 POST 请求的数据所在的位置。我希望将来自 POST 请求的数据传送到那里,以便我的 selected_metersselected_meter_data 查询将按预期工作。

最佳答案

属性选择选项中的值是 ID,但您正尝试使用这些值按名称过滤 MeterData。要么按 id 过滤,要么使用 name 属性作为选项值。

关于python - Django 没有将数据传递给 POST 请求的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244372/

相关文章:

html - 如何将表单选择上的下拉按钮移动到左侧?

python - 在 Python 中编写一个无操作或虚拟类

jquery - 使用jquery解析xml时出现问题

javascript - 如何显示动态添加的元素

javascript - jQuery slideToggle 一次切换多个 Div

html - 在 div 下方居中 div

PHP - 将带有 - 或 + 符号的字符串转换为 HTML

python,修复损坏的 npy 文件。值错误 : total size of new array must be unchanged

python - 从维基百科中的 'infobox geography vcard' 解析官方语言

python - ValueError : This solver needs samples of at least 2 classes in the data, 但数据只包含一个类 : 1. 0