由于某种原因,我无法使其正常工作,所以请帮助我..我有一个下拉列表中有 3 个选项的选择字段。我可以第一时间选择它们,然后提交。然而,在我点击提交后,我想再次选择,但我的下拉列表变空了……我必须刷新页面才能再次出现。为什么?views.py:我把表格放在里面,因为它很短def home(request): class My_form(forms.Form): my_choices = [('TEST', 'TEST'), ('ABC', 'ACB'), ('XZY', 'XZY')] symbol=forms.ChoiceField(choices=my_choices) if request.method == 'POST': test_form = My_form(request.POST) if test_form.is_valid(): symbol = test_form.cleaned_data['symbol'] return render(request, 'blog/home.html',{'symbol':symbol}) else: messages.error(request, "Error") else: test_form = My_form() return render(request, 'blog/home.html', {'test_form':test_form} )模板:{% extends "blog/base.html" %}{% block content %}<form width="600px" action="." method="post" >{% csrf_token %} <div class="row align-items-start"> <div class="col-sm-5"> <label for="symbol">Stocks</label> <select class="form-control" id="symbol" name ="symbol"> {% for key in test_form.symbol %} <option >{{key}}</option> {% endfor%} </select> {{ test_form.errors }} {{ test_form.non_field_errors }} </div> <button type="submit" class="btn btn-primary">Submit</button> </div> </form>{% endblock content %}
1 回答

手掌心
TA贡献1942条经验 获得超3个赞
我认为在函数的 POST 部分,在返回行中,您不会将表单返回到上下文,因此在成功 POST 后模板没有任何表单可以呈现。在 POST 的返回行中尝试类似的操作: return render(request, 'blog/home.html',{'symbol':symbol, 'test_form': test_form})
添加回答
举报
0/150
提交
取消