【问题标题】:Django-admin validation on ManyToMany Field多对多字段上的 Django-admin 验证
【发布时间】:2016-06-16 10:48:18
【问题描述】:

我有一个 django 模型,其中有一个 Module 类,它可以将字段“排序”设置为 4 个值之一(视频、文章、测验、测试)。如果选择了视频或文章,那么我将进行验证以确保字段“文本文件”(这是一个上传的文件)不为空。我想要验证如果选择了测验或测试,那么至少还会添加一个问题。您可以在下面的模块类中看到我尝试的验证,但它不起作用。

这里是models.py:

class Question(models.Model):
    name = models.CharField(max_length=500, verbose_name="Question")
    QUESTION_TYPE = (
        ('Multi', 'Multiple Choice (one correct answer)'),
        ('Check', 'Multiple Answers'),
        ('Matched', 'Match Responses on left with answers on right'),
    )
    sort = models.CharField(
        default="Multi",
        max_length=7,
        verbose_name = "Question Type",
        choices = QUESTION_TYPE)
    answer = models.ManyToManyField(
        Answer,
        through         = 'QuestionAnswer',
        related_name    = 'answer',
        verbose_name    = 'Answer',
        help_text       = 'Answers to this Question'
        )

    def __unicode__(self):
        return u'%s' % (self.name)


class Module(models.Model):
    name = models.CharField(verbose_name='Module Title', max_length=50)
    MODULE_TYPE = (
        ('Video', 'Video'),
        ('Quiz', 'Quiz'),
        ('Article', 'Article'),
        ('Test','Test')
    )
    sort = models.CharField(
        verbose_name='Module Content',
        default="Video",
        max_length=7,
        choices = MODULE_TYPE)
    textfile = models.ForeignKey(DataFile, blank=True, null=True, verbose_name='Data File' )
    description = models.TextField(blank=True, null=True, verbose_name='Module Description')    
    weight = models.IntegerField(default=0, verbose_name="Module Weighting", help_text="Provide the weight you want this module to carry in the course final score.")
    question = models.ManyToManyField(
        Question,
        through         = 'ModuleQuestions',
        related_name    = 'question',
        verbose_name    = 'Question',
        help_text       = 'Questions in this Module'
        )

    def __unicode__(self):
        return u'%s' % (self.name)

    def clean (self):
        if self.sort in ['Video','Article']:
            if not self.textfile:
                 raise ValidationError(
                    _("Videos and Articles must have an linked Data File"),
                    )
        if self.sort in ['Quiz','Test']:
            if not self.question :
                raise ValidationError (
                    _("Quiz and Test Modules must have at least 1 Question"),
                )

class ModuleQuestions(models.Model):
    module = models.ForeignKey(
        Module,
        verbose_name    = 'Module',
        help_text       = 'Module is part of a Course.',
    )
    question = models.ForeignKey(
        Question,
        verbose_name    = 'Question',
        help_text       = 'Quiz and Test Modules have Questions allocated to them.',
    )       
    order = models.IntegerField(
        verbose_name    = 'Order',
        help_text       = 'The order the Questions are presented to the student',
    )

这是我的 admin.py

class ModuleQuestionsInline(admin.TabularInline):
    model = ModuleQuestions
    extra = 1

class ModuleAdmin(admin.ModelAdmin):
    inlines = (ModuleQuestionsInline,)

class QuestionAnswerInline(admin.TabularInline):
    model = QuestionAnswer
    extra = 1


class QuestionAdmin(admin.ModelAdmin):
    inlines = (QuestionAnswerInline,)


admin.site.register(Module, ModuleAdmin)
admin.site.register(Question, QuestionAdmin)

任何帮助将不胜感激。

【问题讨论】:

    标签: python django validation django-models django-admin


    【解决方案1】:

    https://groups.google.com/d/msg/django-users/f_MKyPg_C4w/0WMJol1atOoJ

    基本上,你不能。模型保存后保存m2m字段, 所以你要么得到尚未准备好进行该检查的对象(如 你经历过),或者你将测试 m2m 字段的先前值, 这两者都不是你想要的。

    您可以修改管理界面并在 AdminForm,或者可能捕获 m2m_changed 信号并进行一些检查 在那里,但是您无法在 clean 方法中进行所需的验证。

    【讨论】:

    • 我不喜欢这个答案,因为这不是我想要的,但我同意这是正确的
    猜你喜欢
    • 2016-02-23
    • 2019-04-15
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2012-05-15
    • 2013-11-17
    相关资源
    最近更新 更多