开发者

How to clean a certain field in a InlineFormSet?

开发者 https://www.devze.com 2023-01-15 10:12 出处:网络
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 va开发者_开

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 va开发者_开发技巧lue. 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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号