Как динамически передавать выбор в форму django - PullRequest
0 голосов
/ 25 февраля 2020

Как я могу динамически устанавливать выбор в моей форме? Эти варианты будут меняться в зависимости от маршрута, который выберет пользователь.

forms.py

class RegistrationForm(forms.Form):

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

Я хотел бы установить варианты из моего файла view.py так что я могу установить эти варианты динамически.

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 Ответ

0 голосов
/ 25 февраля 2020

Вы можете сделать

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>)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...