Ambitions
Ambitions

Reputation: 2581

How to limit number of choices of a ManyToManyField to a specific number of choices

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.

Upvotes: 1

Views: 2054

Answers (2)

Ambitions
Ambitions

Reputation: 2581

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

Upvotes: 2

Geoff Walmsley
Geoff Walmsley

Reputation: 11

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

Upvotes: 1

Related Questions