Change the data included in the django form before clearing

I need to change the data included in Formbefore cleaning. I did this, but it looks awful:

    def __init__(self, *args, **kwargs):
        if len(args) > 0:
            data = args[0]
        elif 'data' in kwargs:
            data = kwargs['data']
        else:
            data = None
        if data is not None:
            data['content'] = ' '.join(data['content'].strip().split())
        super(TagForm, self).__init__(*args, **kwargs)

Is there any concise solution?

+5
source share
4 answers

You can compress if/ elif/ elseon one line quite easily:

def __init__(self, *args, **kwargs):
    data = args[0] if args else kwargs.get('data', None)
    if data:
        data['content'] = ' '.join(data['content'].strip().split())
    super(TagForm, self).__init__(*args, **kwargs)

if argsworks the same as if len(args) > 0because the length == 0elements Falseand length > 0elements True.

if dataworks the same as if data is not Nonebecause you assume you datahave at least one key, if it not Noneis anyway, and if it has a key True.

+5
source

data __init__, , Form. , args kwargs.

def __init__(self, data=None, *args, **kwargs):
    if data is not None:
        data = data.copy() # make it mutable
        data['content'] = ' '.join(data['content'].strip().split())
    super(TagForm, self).__init__(data, *args, **kwargs)
+6

:

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: : super(self.__class__, self) , :).

UPD: , , .

+1

, , __init__ . , , , (, ).

0

All Articles