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)
我是新来的django,希望有任何建议。我真的希望能得到帮助。在我的例子中,如何在管理面板中实现验证?禁止将所有答案标记为不正确,禁止将所有答案标记为正确。在这里,BooleanField字段负责这一点。在admin.py模型中,连接是通过“内联”实现的。
发布于 2022-05-18 05:27:01
您可以与表单集的clean()
方法中的主对象一起验证内联对象。为此,您需要为AnswerOptions
定义一个自定义窗体集。
以下是您的问题的解决方案:
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]
附加建议:在Django中,在命名模型时使用单数形式是惯例,所以AnswerOption
和Question
会更好。
https://stackoverflow.com/questions/72279650
复制相似问题