Question

I have a simple form,

class Compose(forms.Form):
    CHOICES = ()    
    recepient = forms.ChoiceField(choices=CHOICES)
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

Chocies are generated as

def mychoiceview(request):
        subscribed_lists, other_lists = getListOfLists(request.user.email)
        for lst in subscribed_lists:
            # list name and list address
            CHOICES = CHOICES + ((lst[1],lst[0]),)

        #Bind data to form and render

Basically, the user is subscribed to certain lists (from a superset of lists) and can choose (via dropdown) which list he/she wants to send the message to.

The problem is that I cannot find how to bind the "CHOICES" to the django form.

Some solutions online include using models.. but I don't have a queryset... just a dynamically generated tuple of ids I want the choicefield to render.

Any ideas ?

Thanks !

Was it helpful?

Solution

@nnmware's solution is correct, but a little too complex/confusing. Below is a more succinct version that works just as well:

class DynamicBindingForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(DynamicBindingForm, self).__init__(*args, **kwargs)
        self.fields['recipient'] = forms.ChoiceField(choices=db_lookup_choices())

where db_lookup_choices is a call to some database or other set of dynamic data and returns a list of pairs for choices: [('val', 'Label'),('val2', 'Label2')]

OTHER TIPS

If you using Class-based view, then:

in view make mixin for sending request in form

class RequestToFormMixin(object):
    def get_form_kwargs(self):
        kwargs = super(RequestToFormMixin, self).get_form_kwargs()
        kwargs.update({'request': self.request})
        return kwargs

class YouView(RequestToFormMixin, CreateView):
    model = YouModel
    # etc

in form make mixin for receive request from view

class RequestMixinForm(forms.Form):
    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request')
        super(RequestMixinForm, self).__init__(*args, **kwargs)
        self._request = request

class Compose(RequestMixinForm):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        super(Compose, self).__init__(*args, **kwargs)
        subscribed_lists, other_lists = getListOfLists(self._request.user.email)
        for lst in subscribed_lists:
            # list name and list address
            CHOICES = CHOICES + ((lst[1],lst[0]),)    
        self.fields['recipient'] = forms.ChoiceField(choices=CHOICES)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top