How can I change a Django form field value before saving?

前端 未结 5 1004
[愿得一人]
[愿得一人] 2021-01-31 08:29
if request.method == \'POST\':
    userf = UsersModelForm(request.POST)
    username = userf.data[\'username\']
    password = userf.data[\'password\']
    passwordrepea         


        
5条回答
  •  时光说笑
    2021-01-31 09:27

    If you need to do something to the data before saving, just create a function like:

    def clean_nameofdata(self):
        data = self.cleaned_data['nameofdata']
        # do some stuff
        return data
    

    All you need is to create a function with the name **clean_***nameofdata* where nameofdata is the name of the field, so if you want to modify password field, you need:

    def clean_password(self):
    

    if you need to modify passwordrepeat

    def clean_passwordrepeat(self):
    

    So inside there, just encrypt your password and return the encrypted one.

    I mean:

    def clean_password(self):
        data = self.cleaned_data['password']
        # encrypt stuff
        return data
    

    so when you valid the form, the password would be encrypted.

提交回复
热议问题