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

Django中HTML Select下拉框提交表单后无法维持选中状态的问题求助

Django中HTML Select下拉框提交表单后无法维持选中状态的问题求助

大家好,我最近在做Django项目时遇到了一个头疼的小问题:提交表单后,HTML的Select下拉框没办法维持之前选中的选项状态。我翻遍了Stack Overflow上的相关解决方案,试过调整模板里的对象引用方式,也修改过视图里的逻辑,但都没能解决问题,想请各位大佬帮忙看看哪里出错了。

下面是我的视图代码和HTML模板代码:

视图代码(views.py)

def profile(request,pk):
    posts = Post.objects.filter(active=True, owner=request.user)
    comments = Comment.objects.filter(post_owner=request.user)

    filter_post = request.GET.get('filter_post')

    if filter_post:
        comments = Comment.objects.filter(post_owner=request.user, post__exact=filter_post)
        ### 试过用post_id、post__id替代post__exact

    return render(request, 'profile.html', {'posts':posts, 'comments':comments, 'filter_post':filter_post})

模板代码(profile.html)

<form method="GET">
    <select class="form-select"  id="filter_post" name='filter_post'>
        <option value=""{% if value == "" %}selected {% endif %}>
            Select post
        </option>
        {% for post in posts %}
        <option value="{{post.id}}" {% if post.id == filter_post %} selected="selected" {% endif %}>
            {{post.title}} - {{post.created}}
        </option>
        {% endfor %}
    </select>
</form>

我尝试了各种组合,包括修改视图里的过滤条件写法(比如用post_id、post__id代替post__exact),还有调整模板里判断选中状态的逻辑,但提交表单后下拉框总是回到默认的“Select post”选项,没法保持我之前选中的那个帖子选项。请问我哪里写错了?

备注:内容来源于stack exchange,提问作者PolarBear

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 10:40:29