10

I need a Django Form Field which will take a list of strings.

I'll iterate over this list and create a new model object for each string.

I can't do a Model Multiple Choice Field, because the model objects aren't created until after form submission, and I can't do a Multiple Choice Field, because I need to accept arbitrary strings, not just a series of pre-defined options.

Anyone know how to do this?

3 Answers 3

8

Just use a regular text field delimited by commas. After you handle the form submission in the view do a comma string split based on that field. Then iterate over each one creating and saving a new model. Shouldn't be too hard.

2
  • 1
    I considered this, but it would be a pretty big break with convention in my API. Nov 29, 2012 at 18:18
  • 2
    I know this is a super old question, but do you know if this still the convention? It seems like they should have something built in for handling lists by now. Jul 18, 2022 at 19:06
2

In my case to process list of strings I used forms.JSONField(decoder="array") in my forms.py in form class

-3

I came up with a solution -- a little hacky but it works for now.

After grabbing the form data, I stash the list in a variable:
event_locations = form_data.get('event_locations', None)

Then I remove it from form_data, so the Django Form never gets the list:

if event_locations:
   del form_data['event_locations']

I instantiate my form with form_data, and handle the list separately:

f = NewEventForm(form_data)
...
for loc in event_locations:
  #create new models here

I realize this doesn't directly solve the question I asked, because we still don't have a Django Form Field taking a list, but it's a way to pass in a list to a view that takes a form and be able to handle it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.