如何在ModelForm中使用admin.TabularInline [英] How to use admin.TabularInline in a ModelForm
问题描述
全文仅验证管理员表单if condition is true
我试图验证一个表单有答案。
为了验证管理员中的表单,您需要创建一个新表单,并告诉admin.ModelAdmin类来使用该表单。
I am trying to validate that a form has an answer. In order to validate a form in the admin you need to make a new form and tell the admin.ModelAdmin class to use that form.
这是否正确?
我已经创建了一个表单,但现在我无法使用我的内联表单。如果我把它放在admin.ModelAdmin中,它仍然显示,我仍然可以填写该部分,但是如果它在帖子数据中,它不会以clean_data的形式出现。
I have created a form but now I can't use my inlines form. If I put it in the admin.ModelAdmin it still shows up and I can still fill that part out but it doesn't appear in the form cleaned_data if though it is in the post data.
如何在QuestionAdminForm中使用ChoiceInline?
How do I use ChoiceInline in QuestionAdminForm?
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4
#TODO: move?
class QuestionAdminForm(forms.ModelForm):
choices = ChoiceInline
class Meta:
model = Question
def clean(self):
data = self.cleaned_data
#logger.info(data)
choices = self.cleaned_data['choices']
#logger.info(data)
if not self.choices_set.filter(
choice=choices.strip(), is_correct=True).exists():
raise forms.ValidationError("Wrong choice!")
# Always return the cleaned data, whether you have changed it or
# not.
return data
class QuestionAdmin(admin.ModelAdmin):
readonly_fields = ('average', 'last_updated')
#list_display = ["question", "module", "average", "quiz"]
#can't have below because M2M question-> module
#list_display = ["question", "module", "average"]
list_display = ["question", "average"]
list_display_links = ["question"]
list_filter = ['modules__name']
search_fields = ["question", "modules__name", "quiz__name"]
inlines = [ChoiceInline]
actions = [duplicate_questions]
form = QuestionAdminForm
推荐答案
这是我根据 Django管理员内联形式的验证依赖于所有表单之间的字段的总和
class CombinedFormSet(BaseInlineFormSet):
# Validate formset data here
def clean(self):
super(CombinedFormSet, self).clean()
for form in self.forms:
if not hasattr(form, 'cleaned_data'):
continue
data = self.cleaned_data
valid = False
for i in data:
if i != {}:
if i['is_correct']:
valid = True
if not valid:
#TODO: translate admin?
raise forms.ValidationError("A Question must have an answer.")
# Always return the cleaned data, whether you have changed it or
# not.
return data
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 4
formset = CombinedFormSet
这篇关于如何在ModelForm中使用admin.TabularInline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!