views:

50

answers:

1

I have these (simplified) models:

class Question(models.Model):
    question = models.CharField(max_length=60)
class Choices(models.Model):
    question = models.ForeignKey(Question)
    text = models.CharField(max_length=60)
    is_correct = models.BooleanField(default=False)

I've made Choices as an inline of Question (in admin). Is there a way to make sure that only one Choice will have is_correct = True?

Ideally, is_correct will be displayed as a radio button when it is displayed in the admin formset (TabularInline).

my admin.py has:

from django.contrib import admin

class OptionInline(admin.TabularInline):
    model = Option
    extra = 5
    max_num = 5

class QuestionAdmin(admin.ModelAdmin):
    inlines = [OptionInline, ]

admin.site.register(QType)
admin.site.register(Question, QuestionAdmin)
A: 

my (not so ideal) solution was to add a validation to the formset, and display a validation error if more than one checkbox is checked:

added this to my admin.py:

from django.forms.models import BaseInlineFormSet from django.forms.util import ValidationError

from models import QType, Question, Option

class  OptionFormSet(BaseInlineFormSet):
    def clean(self):
        if any(self.errors):
            return
        checked = 0
        for i in range(0, self.total_form_count()):
            form = self.forms[i]
            if not form.cleaned_data.has_key('is_correct'):
               continue
            correct = form.cleaned_data['is_correct']
            if correct:
               checked = checked + 1
            if (checked>1):
               raise ValidationError, "Please select only one correct answer."

and my class OptionInline became:

class OptionInline(admin.TabularInline):
    model = Option
    extra = 5
    max_num = 5
    formset = OptionFormSet
azuer88