You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用get_queryset后,如何让Django的POST请求正常工作?

问题:POST提交后设备列表为空

我需要展示用户专属的设备列表,每个设备旁带有复选框,用户可勾选想要在地图上查看的设备,点击提交按钮完成选择(地图部分后续实现)。当前遇到的问题是POST请求无法正常工作:勾选复选框提交后,POST请求会立即触发GET请求,导致页面加载时设备表格为空。

为了让用户仅能查看分配给自己的设备,我使用了get_queryset方法过滤,但查阅相关问题后尝试的解决方案均无效。

views.py 代码片段

class DeviceListView(LoginRequiredMixin, ListView):
    model = Device
    template_name = 'tracking/home.html'
    context_object_name = 'devices'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(who_added=self.request.user)       

    def post(self, request):
        form = SelectForm(request.POST)   
        return render(request, self.template_name, {'form': form})

模板代码片段

<div class="table-responsive">
    <form action="" method="post" name="devices_to_check"> 
        {% csrf_token %}
        <table id="registered_devices" 
        class="table table-striped table-bordered table-hover table-sm" 
        style="width:100%; border: 1px solid black; font-size: 10px">
            <thead class="table-primary" 
            style="text-align:center; border: 1px solid black">
                <tr>
                    <th>IMEI</th>
                    <th>Label</th>
                    <th>Device Type</th>
                    <th>Group</th>
                    <th>Subgroup</th>
                    <th>Description</th>
                    <th>Display</th>
                </tr>    
            </thead>
            
            <tbody>
                {% for device in devices %}
                    <tr>
                        <td>{{device.imei}}</td>
                        <td>{{device.label}}</td>
                        <td style="text-transform:uppercase">{{device.device_type}}</td>
                        <td>{{device.main_group}}</td>
                        <td>{{device.subgroup}}</td>
                        <td>{{device.description}}</td>
                        <td style="text-align:center">
                            <a href="{% url 'device-detail' device.id %}">i    </a>
                            <input type="checkbox" id="{{device.imei}}" name="chk" 
                            value="{{device.imei}}" onclick="show_info_icon()" 
                            class="chckvalues"/>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
            <input type="button" class="btn btn-outline-info" onclick='selects()' 
            value="Select All"/>  
            <input type="button" class="btn btn-outline-info" onclick='deSelect()' 
            value="Deselect All"/>                            
            <button type="submit" class="btn btn-outline-info">Show on Map</button>
    </form>    
</div>

内容的提问来源于stack exchange,提问作者jeff000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:10:43