Django:如何从父模型表单访问内联字段?

时间:2017-04-19 09:16:26

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

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

一个问题可以有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)

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是从内联方访问,而不是从主窗体访问。

创建一个继承自ChoiceForm的{​​{1}},并将ModelForm方法替换为您的方法,例如:

clean()

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