Dynamic choice option for select filed in Multivaluefield

23 views
Skip to first unread message

saranya k

unread,
Oct 14, 2016, 7:13:25 AM10/14/16
to Django users
I want to set choices for ChoiceField in MultiValueField in form init. But its not getting updated.
class
TestField(forms.MultiValueField):
    def __init__(self,*args, **kwargs):
  
        error_messages = {
        'incomplete': 'incomplete',
    }
        a = forms.ChoiceField(choices=((1,'a'),),required=True)
        b =forms.ChoiceField(choices=((2,'b'),),required=True)
        c = forms.ChoiceField(choices=((3,'c'),),required=True )   
        fields = (a,b,c )
        widget = TestWidget(mywidgets=[fields[0].widget, fields[1].widget, fields[2].widget])
        super(TestField, self).__init__(
            error_messages=error_messages, fields=fields,widget=widget,
        require_all_fields=True, *args, **kwargs
    )
    def compress(self, data_list):
        if data_list:  
            return {'academic':data_list[0],'ugs':data_list[1],'stu_sec':data_list[2]}    
  
class TestWidget(widgets.MultiWidget):
    def __init__(self, mywidgets,attrs=None):
        _widgets = (
        widgets.Select(attrs=attrs, choices=mywidgets[0].choices),
        widgets.Select(attrs=attrs,choices=mywidgets[1].choices),
        widgets.Select(attrs=attrs,choices=mywidgets[2].choices),
    )
        super(TestWidget, self).__init__(_widgets, attrs)
  
  
    def decompress(self, value):
        if value:
            return [value['academic'], value['ugs'], value['stu_sec']]
        return [None, None, None]  

 

 

class TestForm(forms.Form):

      t=TestField()

   def __init__(self, *args, **kwargs):
       super(TestForm, self).__init__(*args, **kwargs)
       self.fields['t'].fields[1].choices = ((1,1),)

 


Help me to achieve this…

Constantine Covtushenko

unread,
Oct 15, 2016, 3:53:34 AM10/15/16
to django...@googlegroups.com
Hi Saranya,

Please try in TestForm
self.fields['t'].fields[1].widget.choices = ((1,1),)

Hope it helps

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/518fa1e4-e3de-47fc-8051-22cf19df3de6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages