How can I change a Django form field value before saving?
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.
See the documentation for the save()
method
if request.method == 'POST': userf = UsersModelForm(request.POST) new_user = userf.save(commit=False) username = userf.cleaned_data['username'] password = userf.cleaned_data['password'] passwordrepeat = userf.cleaned_data['passwordrepeat'] email = userf.cleaned_data['email'] new_user.password = new1 new_user.passwordrepeat = new2 new_user.save()
You will have problems if you need to fill form from POST, change any form field value and render form again.Here is solution for it:
class StudentSignUpForm(forms.Form): step = forms.IntegerField() def set_step(self, step): data = self.data.copy() data['step'] = step self.data = data
And then:
form = StudentSignUpForm(request.POST)if form.is_valid() and something(): form.set_step(2) return render_to_string('form.html', {'form': form})