Day 15 of the Anvil Advent Calendar
Build a web app every day until Christmas, with nothing but Python!
Find your reindeer twin with an Anvil-based quiz
We’re all now familiar with the internet trend of personality quizzes. Find out which kind of enriched bread you are by answering questions about your inner demons! Or perhaps you’d like to be assigned a celebrity crush by the galaxy brains behind Buzzfeed.
With today’s app, you can discover which of Santa’s reindeer you are by answering a few simple, sensible questions which are definitely very relevant* to the reindeer you’ll get at the end!
* This is a lie.
To see how it works, clone it here and check out the source code:
Creating a quiz as an Anvil app
You can build just about anything with Anvil, the platform for creating full-stack web apps with nothing but Python. Today, I decided to try my hand at building a simple quiz, where you step through a series of questions and arrive at a result.
The data for each of the questions - the question itself, the text of the answers and the images that accompany each answer - are stored in a Data Table.
Then, to display each question, we can just use Data Bindings to let the QuestionForm populate itself!
Whenever one of the answers is clicked on the QuestionForm, an event is raised on the Form itself so that app advances to the next question until we run out of questions and the answer is displayed.
The AnswerForm works very similarly to the QuestionForm - all the data for the possible answers are stored in a Data Table, and the form uses Data Bindings to display the data in a row from that table. Here’s how it looks:
So how does the app use your answers to choose a reindeer? Well… it doesn’t. The function that chooses an answer from the Answers Data Table does the following:
@anvil.server.callable def get_answer(): from random import randint answer = randint(0, 7) return app_tables.answers.get(answer=answer)
Personality quizzes never really tell you anything of value, so I decided to lean into that and have the app just pick randomly from the 8 reindeer named in the original poem, A Visit From St. Nicholas.
Of course, it would be super easy to store the user’s answers and write an actual function that took those answers and gave a real, relevant result - if you were writing a quiz that had meaningful answers, that is!
Meanwhile, have fun trying to get all the different reindeer, and have a wonderful Advent!
Give the Gift of Python
Share this post: