Reputation: 2581
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:
django-forms
, I am only building an API for a mobile app.Upvotes: 1
Views: 2054
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
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