Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - Django "dynamic" verification form

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

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

1 Reply

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...