1
질문 모델과 선택 모델이 있습니다. 선택은 옳거나 다를 수 있습니다.조건이 참일 경우 관리자 양식 만 확인하십시오.
class Choice(models.Model):
question = models.ForeignKey('Question', related_name='choices')
choice = models.CharField(max_length=255)
is_correct = models.BooleanField(default=False)
times_chosen = models.IntegerField(editable=False, default=0)
def __unicode__(self):
return self.choice + '/' + str(self.times_chosen)
#multiple choice question
class Question(models.Model):
def _get_average(self):
"Returns the average in percent"
if self.times_total == 0:
return 0.0
return (self.times_correct/float(self.times_total)) * 100
def _get_answer(self):
"Returns the answer"
for choice in self.choices.all():
if choice.question == self and choice.is_correct:
return choice.choice
return None
def __unicode__(self):
return self.question
question = models.CharField(max_length=255)
modules = models.ManyToManyField(Module, related_name='questions')
creator = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now=True)
#used for global statistics per question
times_correct = models.IntegerField(editable=False, default=0)
times_total = models.IntegerField(editable=False, default=0)
#Derived values
average = property(_get_average)
answer = property(_get_answer)
처음에는 대답이있을 때만 저장하려고했습니다.
def save(self):
" Make sure that a question has at least one answer "
if self._get_answer():
super(Question, self).save()
하지만 답변 세트가 없기 때문에 질문을 저장할 수없고 저장할 때까지 답변을 설정할 수 없습니다.
질문 양식이있을 때마다 답변이 유효한지 확인해야합니다.
양식은 관리자에 있으며 인라인을 사용합니다. 그래서 나는 새로운 폼 클래스를 만들었고 관리자 대신에 그것을 사용하고 싶습니다.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4
#TODO: move?
class QuestionAdminForm(forms.ModelForm):
class Meta:
model = Question
def clean(self):
data = self.cleaned_data
logger.info(data)
data = self.cleaned_data['choices']
logger.info(data)
#if "[email protected]" not in data:
# raise forms.ValidationError("You have forgotten about Fred!")
# Always return the cleaned data, whether you have changed it or
# not.
return data
class QuestionAdmin(admin.ModelAdmin):
readonly_fields = ('average', 'last_updated')
#list_display = ["question", "module", "average", "quiz"]
#can't have below because M2M question-> module
#list_display = ["question", "module", "average"]
list_display = ["question", "average"]
list_display_links = ["question"]
list_filter = ['modules__name']
search_fields = ["question", "modules__name", "quiz__name"]
inlines = [ChoiceInline]
actions = [duplicate_questions]
form = QuestionAdminForm
그러나 self.cleaned_data에는 선택 항목이 없습니다. 그래서 그 중 하나가 대답인지 확인하기 위해 사용할 수는 없습니다. 여기에 편집
는
creator
u'Siecje'
choices-0-is_correct
u'on'
choices-1-choice
u'No'
choices-0-id
u''
choices-__prefix__-question
u''
choices-1-id
u''
question
u'Question Four?'
choices-0-question
u''
csrfmiddlewaretoken
u'hfRAW8B03as6XN5GpIygJ642VKMN2TPa'
choices-__prefix__-id
u''
choices-3-id
u''
_save
u'Save'
choices-2-question
u''
choices-2-id
u''
choices-MAX_NUM_FORMS
u'1000'
choices-INITIAL_FORMS
u'0'
choices-3-question
u''
choices-3-choice
u'So'
choices-0-choice
u'Yes'
choices-__prefix__-choice
u''
choices-1-question
u''
modules
u'24'
choices-2-choice
u'Maybe'
choices-TOTAL_FORMS
u'4'