Modify data incoming to django form before cleaning

后端 未结 4 901
北恋
北恋 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 08:54

    You can compress the if / elif / else onto one line easily enough:

    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 args works as well as if len(args) > 0 because length == 0 items are False and length > 0 items are True.

    if data works as well as if data is not None because you're assuming that data has at least one key if it's not None anyway, and if it has a key it's True.

提交回复
热议问题