How to pass choices dynamically into a django form

Viewed 1411

How can I set choices dynamically in my form ? These choices will change based on the route the user takes.

forms.py

class RegistrationForm(forms.Form):

    options = ()
    camp_dates = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                         choices=options)

I would like to set the choices from my view.py file so that I can set these choices dynamically.

views.py

def camp_datailed_view(request,slug):

 options = (
    ("1", "Jan"),
    ("2", "Feb"),
    )

 form = RegistrationForm()

 ##How can I pass options into the form field camp_dates as selectable choices



def register(request):

    form = RegistrationForm()

    if request.method == 'POST':

     # create a form instance and populate it with data from the request:
     form = RegistrationForm(request.POST)

     # check whether it's valid:
     if (form.is_valid()):

         return render(request,'camp_registration.html')
     else:
      print (form.errors)

      return HttpResponse("not working")``
1 Answers

You can do

class RegistrationForm(forms.Form):
    camp_dates = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=()
    )

    def __init__(self, *args, **kwargs):
        camp_dates_choices = kwargs.pop('camp_dates_choices', ())
        super().__init__(*args, **kwargs)
        self.fields['camp_dates'].choices = camp_dates_choices


form = RegistrationForm(camp_dates_choices=<DYNAMIC_VALUE>)
Related