我正在尝试建立一个多重选择测试Django应用程序。我有一个名为Answer的模型,另一个模型名为Question。
以下是Answer的内容
class Answer(models.Model):
text = models.CharField(max_length=255)这是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')我只想把other_answers在django-admin中的选择限制在3个答案上。怎么做?
备注:
django-forms,我只是为一个移动应用程序构建一个API。发布于 2019-06-26 02:44:14
谢谢杰夫·沃尔姆斯利的回答,它激励我找到正确的答案。
这就是解决办法:
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发布于 2019-06-25 20:18:52
如果你想把它限制在3个具体的答案上,我想你可以使用至
如果你只想把它限制在最大3,那么你应该使用django模型验证
https://stackoverflow.com/questions/56760890
复制相似问题