23075

Dynamically populating choicefield in Django

Question:

I can't initialize the Choicefield form inside the views.py. I tried passing the option variable in the __init__ function but I got an error:

__init__() takes at least 2 arguments (1 given)` coming from the `form = super(SomeeWizard, self).get_form(step, data, files)

<strong>forms.py</strong>

class SomeForm(forms.Form): def __init__(self, choice, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.fields['choices'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in choice])

<strong>views.py</strong>

class SomeWizard(SessionWizardView): def get_form(self, step=None, data=None, files=None): form = super(SomeWizard, self).get_form(step, data, files) if step == "step2": option = self.get_cleaned_data_for_step("step1")['choice'] choice = Choice.objects.filter(question__text__exact=option) form = SomeForm(choice) return form def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kargs): return render_to_response('done.html')

<strong>EDIT</strong>

I tried Hasan solution and Django Form Wizard is passing {'files': None, 'prefix': 'step2', 'initial': {}, 'data': None} into the **kwarg in the __init__ function of SomeForm.

I printed the content in the **kwarg and I got:

{'files': None, 'prefix': 'step2', 'initial': {}, 'data': None} {'choices': [<Choice: Blue>, <Choice: Red>]}

Answer1:

try this change(I comment changed line):

forms.py:

class SomeForm(forms.Form): def __init__(self, *args, **kwargs): #this line changed choice = kwargs.pop('choice', None) #this line added self.fields['choices'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in choice]) super(SomeForm, self).__init__(*args, **kwargs)

views.py:

class SomeWizard(SessionWizardView): def get_form(self, step=None, data=None, files=None): form = super(SomeWizard, self).get_form(step, data, files) if step == "step2": option = self.get_cleaned_data_for_step("step1")['choice'] choice = Choice.objects.filter(question__text__exact=option) form = SomeForm(choice=choice) #this line changed return form def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kargs): return render_to_response('done.html')

Answer2:

FYI I had to init the form with the data attribute for this to work. For example:

class SomeWizard(SessionWizardView): def get_form(self, step=None, data=None, files=None): form = super(SomeWizard, self).get_form(step, data, files) # determine the step if not given if step is None: step = self.steps.current if step == "2": option = self.get_cleaned_data_for_step("1")['choice'] choice = Choice.objects.filter(question__text__exact=option) ## Pass the data when initing the form, which is the POST ## data if the got_form function called during a post ## or the self.storage.get_step_data(form_key) if the form wizard ## is validating this form again in the render_done methodform form = SomeForm(choice=choice, data=data) return form def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kargs): return render_to_response('done.html')

Otherwise when the form was submitted it just returned my back to this first form. For a full explanation see <a href="https://stackoverflow.com/questions/32740361/django-formwizard-with-dynamic-form-does-not-proceed-to-next-step?noredirect=1#comment53321789_32740361" rel="nofollow">here</a>. I am using django 1.8 though.

Recommend

  • Django form edit problem at intiliazation
  • Listing a ChoiceField in django as Button
  • Dynamic select options not validating Django
  • Custom Templates Django Formwizard
  • Why doesn't copyTo(… PASTE_VALUES) work in the middle of a macro?
  • Django ModelForm not saving data
  • How to know the return address of a function?
  • How to pass props to react component through routing using react-router?
  • Tabs with different sidebars
  • Access 2007 VBA : Building a listbox with selection choices from another list box
  • How to implement 'category' based newsletter
  • Unit Testing the Server Interface for a Silverlight-Facebook Application
  • How to check whether a command can be executed?
  • Mutable values in an object
  • what is the use case for scala List's companion function returning GenericCompanion?
  • webforms : add dynamically in javascript option to a dropdownlist
  • Transaction coordinator for wcf distributed transactions
  • Sharepoint change Content Type in Sharepoint Designer using workflow
  • Radio button show hover between two radio button using jquery
  • acts_as_taggable_on Tags added twice
  • Django Rest Framework: getting lists from query_params without request.getlist
  • Simple command-line app I/O in Dart
  • Refactoring advice: maps to POJOs
  • Want to save selected (i.e., more than 1) enums as string with NHibernate
  • How do I signal completion of my dataflow?
  • Parse a date string in a specific locale (not timezone!)
  • Installing iPhone App to iPhone
  • Spring Data JPA custom method causing PropertyReferenceException
  • How to add date and time under each post in guestbook in google app engine
  • Possible to stop flickering java tooltip in heavyweight mode?
  • How to handle AllServersUnavailable Exception
  • JSON with duplicate key names losing information when parsed
  • Return words with double consecutive letters
  • 0x202A in filename: Why?
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How to stop GridView from loading again when I press back button?
  • Checking variable from a different class in C#
  • Python/Django TangoWithDjango Models and Databases