1

我有两个在 Django 管理员中使用模型表单的基本模型。Models.py 类似于:

class FirstModel(models.Model):
    name = CharField(max_length=100)
    url = URLField()
class OtherModel(models.Model):
    model = models.ForeignKey(FirstModel)
    ##Other fields that show up fine and save fine, but include some localflavor

Forms.py 类似于:

class FirstModelForm(forms.ModelForm):
    def clean(self):
        #call the super as per django docs
        cleaned_data = super(FirstModelForm, self).clean()
        print cleaned_data
    class Meta:
        model = FirstModel
#other modelform is the same with the appropriate word substitutions and one field that gets overridden to a USZipCodeField

这些是堆叠的内联 ModelAdmin,在 admin.py 中没有什么特别之处:

class OtherModelInline(admin.StackedInline):

    model = OtherModel
    fields = (#my list of fields works correctly)
    readonly_fields = (#couple read onlys that work correctly)

class FirstModelAdmin(admin.ModelAdmin):
    inlines = [
        OtherModelInline,
        ]
admin.site.register(FirstModel, FirstModelAdmin)

我确实有一个 User 模型、表单和 ModelAdmin,它继承了 User 和 UserCreationForm 并覆盖了它自己的 clean 方法。这完全符合预期。问题在于FirstModelOtherModel。我在 ModelForm 子类中重写的干净方法,FirstModelForm不做OtherModelForm任何事情。没有抛出异常或打印cleaned_data。根本不值一提。其他一切都按预期工作,但就像我的干净方法甚至不存在一样。我必须错过一些简单的东西,但我看不到是什么。任何帮助都会很棒。谢谢!

4

3 回答 3

1

默认情况下,Django 会为您的模型管理员动态生成模型表单。您必须通过设置 form 属性来指定要使用自定义表单。

class OtherModelInline(admin.StackedInline):

    model = OtherModel
    fields = (...) # if this doesn't work after specifying the form, set fields for the model form instead
    readonly_fields = (#couple read onlys that work correctly)
    form = OtherModelForm

class FirstModelAdmin(admin.ModelAdmin):
    form = FirstModelForm
    inlines = [
        OtherModelInline,
        ]
admin.site.register(FirstModel, FirstModelAdmin)
于 2013-04-25T23:33:52.247 回答
0

您需要cleaned_dataclean表单中的方法返回。如果您查看用于清理相互依赖的字段的文档,您会注意到:

...
# Always return the full collection of cleaned data.
return cleaned_data
于 2013-04-25T21:58:25.540 回答
0

父 'clean' 方法可能没有任何东西能幸存下来。如果您提交的数据由于您的模型设置方式而无法验证,那么cleaned_data 将为空。Timmy 链接的同一个文档中提到了这一点,其中说:

到调用表单的 clean() 方法时,所有单独的字段清理方法都将运行(前两节),因此 self.cleaned_data 将填充到目前为止存活的任何数据。因此,您还需要记住要考虑到您要验证的字段可能无法通过初始单个字段检查的事实。

在这种情况下,如果您有 URLField,则字段验证非常严格,除非您定义“verify_exists=False”,否则它还会检查您是否输入了返回 404 的 URL。在您的情况下,您需要如果你想允许这样做:

class FirstModel(models.Model):
    name = CharField(max_length=100)
    url = URLField(verify_exists=False)

除此之外,我不知道会发生什么。

于 2013-04-25T23:01:34.567 回答