1

I am trying to build a multiple choice quizzes Django app. I have a model named Answer, and another model named Question.

Here are the contents of Answer:

class Answer(models.Model):
    text = models.CharField(max_length=255)

and this is Question:

class Question(models.Model):
    text = models.CharField(max_length=255)
    correct_answer = models.ForeignKey('Answer', on_delete=models.CASCADE, related_name='correct_answers')
    other_answers = models.ManyToManyField('Answer')

I want to limit the number of choices of other_answers in django-admin to 3 answers only. How to do that?

Notes:

  1. I am ok with re-modeling my models.
  2. I will not use django-forms, I am only building an API for a mobile app.
Ambitions
  • 2,369
  • 3
  • 13
  • 24

2 Answers2

2

Thanks for Geoff Walmsley's answer which inspired me for the correct answer.

This is the solution:

admin.py:

from django.contrib import admin
from django.core.exceptions import ValidationError
from .models import Question
from django import forms


class QuestionForm(forms.ModelForm):
    model = Question

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get('other_answers').count() != 3:
            raise ValidationError('You have to choose exactly 3 answers for the field Other Answers!')


@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    form = QuestionForm
Ambitions
  • 2,369
  • 3
  • 13
  • 24
1

If you want to limit it to 3 specific answers I think you can use limit_choices_to

If you want to just limit it to a max of 3 then you should use django model validation

  • Thanks for your contribution. I want `other_answers` to be exactly 3 answers. I tried your solution but it failed as `clean` function is called before saving the record, which means `self.other_answers.count()` is always zero. However, your answer inspired me to the correct answer. Please read my answer if you want to have an idea about how to do it. – Ambitions Jun 26 '19 at 02:38