Validation with checking all model objects. Django

Viewed 50
class Questions(models.Model):
    question = models.CharField(max_length=350)

class AnswerOptions(models.Model):
    answer = models.CharField(max_length=150)
    yesorno = models.BooleanField(default=False)
    question = models.ForeignKey('Questions', 
    on_delete=models.CASCADE)

I am new to django and would appreciate any suggestions. I really hope for help. How in my case to implement validation in the admin panel? it is necessary to prohibit marking all answers as incorrect and all answers as correct. here the BooleanField field is responsible for this. in the admin.py model, the connection is implemented through “inline”.

1 Answers

You can validate the inline objects together with the main object in the clean() method of the formset. For that you need to define a custom formset for AnswerOptions.

Here is a working solution for your question:

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

from .models import AnswerOptions, Questions


class AnswerOptionsInlineFormSet(BaseInlineFormSet):
    def clean(self):
        super().clean()

        answers_yesno = []
        for form in self.forms:
            if not form.is_valid():
                return  # other errors exist, so don't bother
            if form.cleaned_data and not form.cleaned_data.get("DELETE"):
                answers_yesno.append(form.cleaned_data.get("yesorno"))

        if answers_yesno:  # check only if we have any clean answers
            if all(answers_yesno):
                raise ValidationError("Not every answer can be 'yes'")
            if not any(answers_yesno):
                raise ValidationError("Not every answer can be 'no'")


class AnswerOptionsInline(admin.TabularInline):
    model = AnswerOptions
    formset = AnswerOptionsInlineFormSet


@admin.register(Questions)
class QuestionsAdmin(admin.ModelAdmin):
    inlines = [AnswerOptionsInline]

Additional advice: In Django it is convention to use the singular form when naming Models, so AnswerOption and Question would be better.

Related