首页 > 解决方案 > 如何预填充 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,
            )

正确的方法是什么?谢谢

标签: djangodjango-forms

解决方案


将列表作为选项分配给表单字段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)

推荐阅读