Search code examples
pythondjangodjango-formschoicefield

Django forms.Choicefield get selected Choice


I need to get the selected Value of a forms.Choicefield for an if/else statement which produces another forms.Choicefield based on the selected Value

forms.py:

class ReceiverForm(forms.Form):
receivers = forms.ChoiceField(choices=db_mails(), required=True, label='Receivers')

if db_certs(<- selected value from receivers ChoiceField ->):
    print "cert found"
    encryption = forms.ChoiceField(choices=EncryptionChoiceAll, initial='smime_mail', required=True, label='Encryption')
else:
    print "no cert found"
    encryption = forms.ChoiceField(choices=EncryptionChoiceNoCert, initial='smime_mail', required=True, label='Encryption')

db_mails() and db_certs(mail) are working as expected

Is there a way to achieve what i need in forms.py or am I totally wrong with the design?


Solution

  • When the form is built and you specify the choice list, you have no way to know which value is selected, as:

    1. You create an instance of the form class
    2. This instance is used to create the view (On a GET request). The user can modify the selection
    3. He submits the form. For this you create an instance of the class, which is filled with the POST values.

    So at the time you create the class you do not have the information.

    There are possibilities to have dynamic values in one choice, depending on the other one, but this needs to be done on the client side, when the user changes the selection:

    • Use javascript/jquery to update the list of choices depending on the answer. For this, you could have hidden values in the HTML file, and Javascript will update the list from these hidden values.
    • If the choice to update is more dynamic (For example a list of towns depending on the post code), you still need to use Javascript, but with Ajax that will send an asynchronous request to the server to get the list and update the choices.

    There are plenty of tutorials to do this, and this is not directly linked to Django. As an example:

    https://css-tricks.com/dynamic-dropdowns/