cegthgtlhj
cegthgtlhj

Reputation: 311

How to prepopulate Django (non-Model) Form (how to pass the values list from view.py to the ChoiceField in the Form)?

I have read similar threads, but found nothing. The rest of my code works pretty well. The problem is here: I generate a list list_to_prepopulate_the_form1 consisting of 2x tuples in my views.py and need to pass this list to the form in 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,
            )

What is the right way to do it? Thank you

Upvotes: 0

Views: 53

Answers (1)

JSRB
JSRB

Reputation: 2623

assign the list as choices to the form field druckstufe like so:

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)

Upvotes: 1

Related Questions