Django Form Form class alternative to the null value of None

Recent Form used when writing the project, found that this class everything is good, some is the default assignment null values really are not to my liking.
Access to information, after the official documentation found no way to set the value. So began my step on pit road ......
but now the perfect solution, the method is also very simple.
Simply put: to build a base class, heavy-duty form.Forms the clean function.
Examples are given below:

class BaseForm(forms.Form):
    # 重载clean方法
    def clean(self):
        # 遍历字典
        cleaned_data = {}
        for key, value in self.cleaned_data.items():
            if value == None:
                cleaned_data[key] = self.fields[key].initial
            else:
                cleaned_data[key] = value
        return cleaned_data

I chose to set the value of his property for the Field of the initial value, easy to maintain me.
Specific Form class inherits BaseForm class can be.
Such as:

class NewForm(BaseForm):
    name = forms.CharField(label='名称')
    age = form.IntegerField(
        label='年龄',
        required=False
)

Test data:

name=test&age=

age value is empty, if at this time form.Form inherited class, cleaned_data values:

{'name': 'test', 'age': None}

This is the result I want to see, although some exist empty_value Field property can be set, but at the moment IntegerField field and not the property values, using the proposed method can modify the value of the initial value will be None attributes defined for themselves.
If this article help you, remember a few clicks of the top, so that more people see yo.

Guess you like

Origin www.cnblogs.com/yunen/p/11854418.html