django - 如何预填充 Django(非模型)表单(如何将值列表从 view.py 传递到表单中的 ChoiceField)?
问题描述
我读过类似的主题,但一无所获。我的其余代码运行良好。问题就在这里:我在views.py中生成了一个list_to_prepopulate_the_form1
由2x元组组成的列表,并且需要将此列表传递给forms.py中的表单
views.py
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from .models import *
def n01_size_kss(request):
if request.method == 'POST':
form = KSS_Form(request.POST)
context = {'form':form}
if form.is_valid():
filtertype, context = n01_context_cleaned_data(form.cleaned_data)
if filtertype != "none":
list_to_prepopulate_the_form1 = prepare_dictionary_form2(context)
form1 = KSS_Form1(initial={'list1'=list_to_prepopulate_the_form1})
context = {'form':form1, **context}
return render(request, 'af/size/01_kss_size2.html', context)
else:
context = {'form':KSS_Form()}
return render(request, 'af/size/01_kss_size1.html', context)
forms.py
from django import forms
from django.conf.urls.i18n import i18n_patterns
class KSS_Form1(forms.Form):
druckstufe = forms.ChoiceField(\
required=True, \
label=_("Specify desired presure stage:"), \
initial="1", \
disabled=False, \
error_messages={'required':'Please specify desired pressure stage'}, \
choices = list1,
)
正确的方法是什么?谢谢
解决方案
将列表作为选项分配给表单字段druckstufe
,如下所示:
views.py
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from .models import *
def n01_size_kss(request):
if request.method == 'POST':
form = KSS_Form(request.POST)
context = {'form':form}
if form.is_valid():
filtertype, context = n01_context_cleaned_data(form.cleaned_data)
if filtertype != "none":
list_to_prepopulate_the_form1 = prepare_dictionary_form2(context)
form1 = KSS_Form1()
# magic here
form1.fields['druckstufe'].choices = list_to_prepopulate_the_form1
context = {'form':form1, **context}
return render(request, 'af/size/01_kss_size2.html', context)
else:
context = {'form':KSS_Form()}
return render(request, 'af/size/01_kss_size1.html', context)
推荐阅读
- php - 查询json中的数据
- python - 我正在尝试过滤行,但它们仍然出现在我的箱线图中
- wso2 - WSO2 流处理器是否支持多租户?
- python - Docutils在nodes.Text中文本和原始资源之间的区别?
- python - 为什么我的变量名在 root 中定义但在 Top-level 中无法识别?
- python - ModuleNotFoundError:Pycharm 中没有名为“dns”的模块
- vue.js - Vuex 异步/等待调度
- java - 如何使用 swagger、openapi 和生成器处理不兼容的 api 更改
- python - Selenium webdriver python无法上传文件-send_keys抛出ElementNotInteractable
- python - 重定向到 django 上的不同页面