Modify data incoming to django form before cleaning

后端 未结 4 921
北恋
北恋 2021-01-12 08:28

I need do modify data incoming to Form before cleaning. I made it work, but It looks awful:

    def __init__(self, *args, **kwargs):
        if          


        
4条回答
  •  长发绾君心
    2021-01-12 09:11

    I found another solution:

    def clean(self, *args, **kwargs):
        data = dict(self.data)
        if 'content' in data:
            content = data['content']
            if isinstance(content, list):
                content = content[0] # QueryDict wraps even single values to list
            data['content'] = ' '.join(content.strip().split())
        self.data = data # I do this trick becouse request.POST is immutable
        return super(MyForm, self).clean(*args, **kwargs)
    

    UPD: error fix: super(self.__class__, self) may cause infinite recursion if I use form inheritance :).

    UPD: seems still have troubles, and not work correctly.

提交回复
热议问题