如何清理 InlineFormSet 中的某个字段?

发布于 2024-09-18 06:17:00 字数 292 浏览 3 评论 0原文

我需要清理内联表单集中的特定字段,但我不知道该怎么做。

我尝试过使用表单集 def clean(self) 方法,但不知道在哪里保存清理后的值。如果我尝试将清理后的值设置为 forms[0].data['field'] 我收到“此 QueryDict 实例是不可变的”错误。

在“正常”形式中,它通过使用 def clean_fieldXY(self) 方法来工作,在该方法中我返回 clean_value

请帮忙。

I need to clean a specific field in an inline formset, and I can't figure out how to do it.

I've tried with the formsets def clean(self) method but don't know where to save the cleaned value. If I try to set the cleaned value to forms[0].data['field'] I get "This QueryDict instance is immutable" error.

In "normal" forms it works by using the def clean_fieldXY(self) method in which I return cleaned_value.

Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方。的韩爷 2024-09-25 06:17:00

您可以将内联表单集设置为使用表单类,然后可以为该字段创建一个 clean 函数。

myapp/forms.py 中:

class InlineFormsetForm(forms.Form)
    myfield = forms.CharField(required=False, max_length=50)

    def clean_myfield(self):
        data = self.cleaned_data['myfield']
        if data == 'badinput':
            raise forms.ValidationError("I hates it!")
        return data

然后,在 myapp/views.py

from myapp.forms import InlineFormsetForm
from myapp.models import ParentRecord, ChildRecord

def editmything(request):
    MyFormSet = inlineformset_factory(ParentRecord, ChildRecord, form=InlineFormsetForm)

You can set the inline formset to use a form class, and then you can create a clean function for the field.

In myapp/forms.py:

class InlineFormsetForm(forms.Form)
    myfield = forms.CharField(required=False, max_length=50)

    def clean_myfield(self):
        data = self.cleaned_data['myfield']
        if data == 'badinput':
            raise forms.ValidationError("I hates it!")
        return data

Then, in myapp/views.py

from myapp.forms import InlineFormsetForm
from myapp.models import ParentRecord, ChildRecord

def editmything(request):
    MyFormSet = inlineformset_factory(ParentRecord, ChildRecord, form=InlineFormsetForm)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文