2

I made a SelectField like this:

# constants.py
QUESTION_LIST = {}
QUESTION_LIST['QuestionOne'] = { 'disagree-strong': "Strongly Disagree", 'agree-strong': "Strongly Agree" }

#forms.py
from constants import *
typeone = SelectField('QuestionOne', 
      choices=QUESTION_LIST['QuestionOne'].iteritems(), 
      description='Answer the question')

So when you load the page, it shows the choices. I pick the choice, press submit and it says "this is not a valid choice" and it blanks out the select field.

Then when you refresh the page, it's as if the code is broken and it doesn't show choices anymore... It's an empty dropdown/select field.

What am I doing wrong?

EDIT: For some reason, when you put the iteritems in the view instead of the form ,everything works. Some sort of quirk with Flask-WTF where if you don't use their format it seems to delete the choices after you submit form.

Dexter
  • 6,170
  • 18
  • 74
  • 101

3 Answers3

9

Maybe the problem is that your keys in dict are a strings. I had this issue before, so maybe something like this would help:

typeone = SelectField("Question1", coerce=str, choices=QUESTION_LIST['QuestionOne'])

This coerce thingie helped. What happens I think that all POST data is unicode and by default coerce is also equals to unicode (at least in WTF forms, need to check Flask-WTF extension if you do use one). And your choices keys are strings.

Ignas Butėnas
  • 6,061
  • 5
  • 32
  • 47
  • 1
    When I add `print ("pre choice", self.choices, self.data)` in `pre_validate`. My situation got: `(u'pre choice', [(1, 'Question'), (2, 'Artical'), (3, 'movie')], u'2').` . I think when it failed .It always has its reason. – jiamo Mar 17 '16 at 08:16
  • In my case, adding `coerce=int` solves my issue. Since the number type of this field in MySQL is `int`, but all `values` from form.SelectField are `str`. They do not match. – Light.G Feb 21 '19 at 10:54
0

You are passing a set instead of a dict. Replace the commas in your QUESTION_LIST definition with colons. Actually the call to .iteritems() should already fail...

QUESTION_LIST['QuestionOne'] = { 'disagree-strong': "Strongly Disagree",
                                 'agree-strong': "Strongly Agree" }
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    Sorry you are right I wrote the pseudo code incorrectly. I did write it correctly in the actual code. So it is correct--still doesn't work tho. My error is different, that's why iteritems wasn't failing. – Dexter Jan 07 '13 at 00:06
0

For some reason, when you put the iteritems in the view instead of the form ,everything works. Some sort of quirk with Flask-WTF where if you don't use their format it seems to delete the choices after you submit form.

So just moving the .iteritems() code into the VIEW, by typing form.question_field.choices = QUESTION_LIST['QuestionOne'].iteritems(); Works better than using iteriterms inside the form file.

Dexter
  • 6,170
  • 18
  • 74
  • 101