• 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 8/25/21

Use Advanced Functionalities of Django Models and Forms

Log in or subscribe for free to enjoy all this course has to offer!

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 called  quizzes .

  • 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  called  QuizForm  . How do you implement it?

    • Use a  HiddenField  to give each instance of  QuizForm  a unique field. Check for the presence of this field in the  POST  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 has  ForeignKey  relationships to the  Quiz  model and  User  model. Use this model to store the quiz’s author.

    • Define a  ForeignKey  named  author  linking to the  User  model on the  Quiz  model. Store the author in this field.

    • Define a  ManyToManyField  named  author  linking to the  User  model on the  Quiz  model. Store the author in this field.

    • Define a  OneToOneField  named  author  linking to the  User  model on the  Quiz  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  called  moderators  and assign users to it appropriately. Define a custom permission  'quizzes.deactivate_quiz'  and assign this permission to the  moderators  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  called  moderators  and assign users to it appropriately. Assign the  'quizzes.change_quiz'  permission to the  moderators  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.