Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to create a verification form in Django that presents a user with a list of choices, only one of which is valid.

For example, for a user whose favourite pizza toppings includes pineapple and roquefort—

What is your favourite pizza topping?

  • Ham
  • Pineapple
  • Anchovie

The choices should be random every time, in both order and values, but always have one valid answer. For example, if the user refreshes the page, the form might be—

What is your favourite pizza topping?

  • Mozarella
  • Ham
  • Roquefort

How do I build such a form? I'm swamped. We have to record somewhere what the valid choice is for a specific form:

  • Create entries in the database for each question (not scalable)?
  • Set it in the session (hacky)?
  • Based on user ID (could be predictible)?

Edit—We do store the list of pizza toppings in the database—

class UserProfile(Model):
    favourite_pizza_toppings = ManyToManyField(PizzaTopping)

What I want is a form such as—

class QuestionForm(Form):
    questions = ChoiceField(choices=(('a', RANDOMLY_CHOSEN_OPTION_A),
                                     ('b', RANDOMLY_CHOSEN_OPTION_B),
                                     ('c', RANDOMLY_CHOSEN_OPTION_C)))

Where, each time it's instantiated, all RANDOMLY_CHOSEN_OPTION are chosen randomly from PizzaTopping.objects.all, with only one being a PizzaTopping also in UserProfile.favourite_pizza_toppings.

We'll need to verify the form when the user POSTs it though—and that's the tricky bit. We have to somehow record which is the valid choice (a, b, or c) for each instantiated form. How can we do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
200 views
Welcome To Ask or Share your Answers For Others

1 Answer

You will need to build up the choices in the the form init method, otherwise the form elements choices will be the same each time the page loads (they won't change).

class QuestionForm(Form):
    questions = ChoiceField()

    def __init__(self, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        self.fields['questions'].choices = set_up_choices() # function that creates list

    clean_questions(self):
        # do your validation of the question selection
        # here you could check whether the option selected matches
        # a correct value, if not throw a form validation exception
        return self.cleaned['questions']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...