【问题标题】:Django: how to access inline fields from parent model form?Django:如何从父模型表单访问内联字段?
【发布时间】:2017-09-15 10:14:06
【问题描述】:

这是一个简单的多项选择应用程序。

一个问题可以有 4 个选项。

在管理面板中,当保存新问题时,我想检查空的选项数量(没有单词),但我不知道如何访问这 4 个选项。

如何在 QuestionForm 的 clean() 函数中访问选项的值?

#model.py
class Question(models.Model):
    question = models.CharField(max_length = 250)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice = models.CharField(max_length = 250)

#admin.py
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 4
    can_delete = False
    max_num = 4 # fix to have 4 choices


class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = '__all__'

    def clean(self):
        """
        HERE, i want to access the 4 choices model
        """
        return self.cleaned_data

class QuestionAdmin(admin.ModelAdmin):
    form = QuestionForm  
    inlines = [ChoiceInline]           


admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin)

【问题讨论】:

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


    【解决方案1】:

    一种方法是从内联端访问,而不是从主窗体访问。

    创建一个继承自ModelForm 的ChoiceForm,并将clean() 方法替换为您的方法,例如:

    class ChoiceForm(forms.ModelForm):
        def clean(self):
            cleaned_data = super(ChoiceForm, self).clean()
            for f in self.forms:
                 f.cleaned_data['choice']  # contains the text you want
                 # so you can check if it's empty and raise ValidationError()
                 # if needed
            return self.cleaned_data
    

    详情请查看https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#overriding-clean-on-a-modelformset。

    【讨论】:

      猜你喜欢
      • 2015-11-15
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 2011-03-13
      • 2017-12-15
      • 2018-07-18
      相关资源
      最近更新 更多