gpt4 book ai didi

Django 表单验证取决于表单集中的数据

转载 作者:行者123 更新时间:2023-12-02 05:42:11 25 4
gpt4 key购买 nike

我有以下代码:

from django import forms
from django.core.exceptions import ValidationError

class MyAdminForm(forms.ModelForm):
class Meta:
model = MyModel

def clean(self):
cleaned_data = self.cleaned_data
max_num_items = cleaned_data['max_num_items']
inline_items = cleaned_data.get('inlineitem_set', [])

if len(inline_items) < 2:
raise ValidationError('There must be at least 2 valid inline items')

if max_num_items > len(inline_items):
raise ValidationError('The maximum number of items must match the number of inline items there are')

return cleaned_data

我以为我可以从cleaned_data访问表单集(通过使用cleaned_data['inlineitem_set']),但事实似乎并非如此。

我的问题是:

  1. 如何访问表单集?
  2. 我是否需要使用自定义验证创建自定义表单集才能使其正常工作?
  3. 如果我需要这样做,如何在其 clean 方法中访问表单集的“父”表单?

最佳答案

我刚刚为我自己的项目解决了这个问题。正如您的第二个问题中所建议的,确实需要访问父表单的任何内联表单集验证都需要位于 clean 中。方法BaseInlineFormset子类。

令人高兴的是,父表单的实例在内联表单集的 clean 之前创建(或者从数据库检索,如果您要修改而不是创建它)。被调用,并且它可以作为 self.instance 在那里使用。 .

from django.core.exceptions import ValidationError
class InlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
try:
forms = [f for f in self.forms
if f.cleaned_data
# This next line filters out inline objects that did exist
# but will be deleted if we let this form validate --
# obviously we don't want to count those if our goal is to
# enforce a min or max number of related objects.
and not f.cleaned_data.get('DELETE', False)]
if self.instance.parent_foo == 'bar':
if len(forms) == 0:
raise ValidationError(""" If the parent object's 'foo' is
'bar' then it needs at least one related object! """)
except AttributeError:
pass

class InlineAdmin(admin.TabularInline):
model = ParentModel.inlineobjects.through
formset = InlineFormset

这里的 try- except 模式是防止 AttributeError我自己没有见过这种极端情况,但当我们尝试访问cleaned_data时显然会出现这种情况。验证失败的表单属性(在 self.forms 中)。从https://stackoverflow.com/a/877920/492075了解到这一点

(注意:我的项目仍在 Django 1.3 上;尚未在 1.4 中尝试过)

关于Django 表单验证取决于表单集中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com