Radio buttons in django admin

I am creating a quiz app in django. here is the model:


    class Quiz(models.Model):
        title = models.CharField(max_length=200)
        description = models.TextField()
        publish = models.BooleanField(default=False)

        def __unicode__(self):
            return self.title

    class Question(models.Model):
        quiz = models.ForeignKey(Quiz)
        question = models.TextField()
        hint = models.TextField()

        def __unicode__(self):
            return self.question

    class Option(models.Model):
        question = models.ForeignKey(Question)
        option = models.CharField(max_length=250)
        correct = models.BooleanField(default=False)

        def __unicode__(self):
            return self.title

Each question can only have one answer. This is where the problem comes in. I haven't been able to figure out how to write the admin form for Option model such that for each question, only one of the options can have correct=True.

I can use radio buttons for each question but don't know how to restrict them such that only one can be selected for one foreign key.


I'm not sure how that can be done with reverse look up.

I know this is not exactly what you want, but is quite close. Can you go ahead and try this in the admin.py

admin.site.register(Quiz)
#admin.site.register(Option) #Include this if required

class OptionInline(admin.TabularInline):
    model = Option

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

I understood your question like this: you want to change your code because only one option should be right. Why don't you add this line to Question:

right_answer = models.ForeignKey(Option)

Like this, you needn't the boolean correct . Your also could add a Manager to this who returns any option which should be chooseable (you override the method get_queryset() , and this manager should have this line at get_qeryset(): q.option_set.all() where q is there Question. (Without this any option, although its matched with another Question, could be marked.)

I'm not sure whether the secont part would work neither whether its a good way, but the first part is the important one.

链接地址: http://www.djcxy.com/p/56512.html

上一篇: 在使用django智能选择时,'NoneType'对象不可下标

下一篇: django管理员中的单选按钮