12 hours
- Medium
Free online content available in this course.
course.header.alt.is_video
course.header.alt.is_certifying
Got it!Last updated on 3/2/22
Use Advanced Functionalities of Django Models and Forms
Evaluated skills
- Use advanced functionalities of Django models and forms
Description
For the following questions, refer to the following scenario:
You are working on a site that allows users to share quizzes with their friends. The quizzes are stored in a
Quiz
model, which is located in an app calledquizzes
.
Question 1
You are asked to build a page from which you can create multiple quizzes at the same time. Quizzes are created using a
ModelForm
calledQuizForm
. How do you implement it?Use a
HiddenField
to give each instance ofQuizForm
a unique field. Check for the presence of this field in thePOST
data to distinguish between forms.Use the
modelformset_factory
method to create formset. Use this formset to host multiple instances of the QuizForm on the same page.Include several different forms under different
<form>
tags in the template. When one form is posted, the data from all of them will be sent to the server.
Question 2
Each quiz can only have one author. What is the most efficient way of storing this in the database?
Define a new model
QuizUser
that hasForeignKey
relationships to theQuiz
model andUser
model. Use this model to store the quiz’s author.Define a
ForeignKey
namedauthor
linking to theUser
model on theQuiz
model. Store the author in this field.Define a
ManyToManyField
namedauthor
linking to theUser
model on theQuiz
model. Store the author in this field.Define a
OneToOneField
namedauthor
linking to theUser
model on theQuiz
model. Store the author in this field.
Question 3
You are asked to give moderators the power to deactivate quizzes but not the ability to edit or delete them. How do you implement this?
Create a
Group
calledmoderators
and assign users to it appropriately. Define a custom permission'quizzes.deactivate_quiz'
and assign this permission to themoderators
group. Use this permission to restrict access to the view from the quizzes that can be deactivated.Hard code a list of IDs into your settings matching those of the moderators. Check if the user who is logged in is on this list in the view handling post deactivation and grant access as appropriate.
Create a
Group
calledmoderators
and assign users to it appropriately. Assign the'quizzes.change_quiz'
permission to themoderators
group. In the view, check if the user has the'quizzes.change_quiz'
permission. If so, only give the user the option to deactivate the quiz, and not to edit it.
- Up to 100% of your training program funded
- Flexible start date
- Career-focused projects
- Individual mentoring