Django dynamic verification form

2024/10/14 13:24:38

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?

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 listclean_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 exceptionreturn self.cleaned['questions']
https://en.xdnf.cn/q/117952.html

Related Q&A

Any method to denote object assignment?

Ive been studying magic methods in Python, and have been wondering if theres a way to outline the specific action of:a = MyClass(*params).method()versus:MyClass(*params).method()In the sense that, perh…

Delete lines found in file with many lines

I have an Excel file (.xls) with many lines (1008), and Im looking for lines that have anything with 2010. For example, there is a line that contains 01/06/2010, so this line would be deleted, leaving …

Combining semaphore and time limiting in python-trio with asks http request

Im trying to use Python in an async manner in order to speed up my requests to a server. The server has a slow response time (often several seconds, but also sometimes faster than a second), but works …

Import of SWIG python module fails with apache

Importing a python mdule throws an exception in django when I run with apache. The same source code works fine with the django development server. I can also import the module from the command line. Th…

Pro-Football-Reference Team Stats XPath

I am using the scrapy shell on this page Pittsburgh Steelers at New England Patriots - September 10th, 2015 to pull individual team stats. For example, I want to pull total yards for the away team (46…

How to delete the last item of a collection in mongodb

I made a program with python and mongodb to do some diaries. Like thisSometimes I want to delete the last sentence, just by typing "delete!" But I dont know how to delete in a samrt way. I do…

Python+kivy+SQLite: How to set label initial value and how to update label text?

everyone,I want to use kivy+Python to display items from a db file. To this purpose I have asked a question before: Python+kivy+SQLite: How to use them together The App in the link contains one screen.…

how to debug ModelMultipleChoiceField [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 7 years ago.Improve…

Standardization/preprocessing for 4-dimensional array

Id like to standardize my data to zero mean and std = 1. The shape of my data is 28783x4x24x7, and it can thought of as 28783 images with 4 channels and dimensions 24x7. The channels need to be standar…

My Python number guessing game

I have been trying to make a number guessing game for Python and so far it has altogether gone quite well. But what keeps bugging me is that it resets the number on every guess so that it is different,…