如何在django管理表单中应用条件?

时间:2013-08-13 04:27:03

标签: django django-admin

我在Django中有这样的模型:

from django.db import models


class Navigation(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name


class Question(models.Model):
    question = models.TextField()
    publication_date = models.DateField()
    is_active = models.BooleanField(default=1)
    is_premium = models.BooleanField(default=0)

    def __unicode__(self):
        return self.question


class QuestionType(models.Model):
    question = models.OneToOneField(Question)
    question_types = (
                      (1, 'Multiple Choice'),
                      (2, 'Text Answer')
                      )
    type = models.IntegerField(choices=question_types, verbose_name="Select Question Type")


class Category(models.Model):
    question = models.OneToOneField(Question)
    navigation = models.OneToOneField(Navigation)
    choices_options = (
        (1, 'Begineer'),
        (2, 'Intermediate'),
        (3, 'Expert')
    )

    choices = models.IntegerField(choices=choices_options, verbose_name="Select level")


class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)


    def __unicode__(self):
        return self.choice_text

class Answer(models.Model):
    question = models.OneToOneField(Question)
    choice = models.OneToOneField(Choice)

我有这样的admin.py:

from django.contrib import admin
from quiz.models import Navigation, Category, Question, Choice, Answer, QuestionType



class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3


class CategoryInline(admin.TabularInline):
    model = Category


class QuestionTypeInline(admin.TabularInline):
    model = QuestionType

class AnswerInline(admin.TabularInline):
    model = Answer

class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
    (None,
    {'fields': ['question']}),
    ('Date information', {'fields': ['publication_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline, CategoryInline, AnswerInline, QuestionTypeInline]

    # Display two headings while displaying all the questions
    list_display = ('question', 'publication_date')

    # Add filter option
    list_filter = ['publication_date']

    # Add search capability
    search_fields = ['question']

    # Show the latest elements by default
    date_hierarchy = 'publication_date'




admin.site.register(Question, QuestionAdmin)
admin.site.register(Navigation)

有两种类型的问题:Multiple Choice questions, text based questions.因此,在创建问题时,如果用户选择多项选择问题,我想显示选项,如果用户选择基于文本的问题,则显示基于一个输入的文本。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

  

因此,在创建问题时,我想显示用户的选择   选择多项选择问题,并根据一个输入显示文本   用户选择基于文本的问题。我怎么能这样做?

你需要一些javascript,因为这是在创作过程中发生的。

请按照以下步骤操作:

  1. 在QuestionAdmin中更改创建模板
  2. 在这个新模板中添加一些javascript来隐藏这两个字段
  3. 添加javascript以根据选择显示相应的字段
  4. 如果有人没有javascript工作,他们会看到这两个字段。

    如果您在使用其中一个步骤时遇到问题,请显示您的代码。