问题描述
if request.method == 'POST':
userf = UsersModelForm(request.POST)
username = userf.data['username']
password = userf.data['password']
passwordrepeat = userf.data['passwordrepeat']
email = userf.data['email']
我试过了:
tempSalt = bcrypt.gensalt()
password = bcrypt.hashpw(password,tempSalt)
passwordrepeat = bcrypt.hashpw(passwordrepeat,tempSalt)
userf.data['password'] = password
userf.data['passwordrepeat'] = passwordrepeat
但是我出错了.如何在保存前更改 userf.data['password']
和 userf.data['passwordrepeat']
的值?
But i got error. How can i change the value of userf.data['password']
and userf.data['passwordrepeat']
before saving?
错误:
AttributeError at /register
This QueryDict instance is immutable
Request Method: POST
Request URL: http://127.0.0.1:8000/register
Django Version: 1.3.1
Exception Type: AttributeError
Exception Value:
This QueryDict instance is immutable
Exception Location: /usr/local/lib/python2.6/dist-packages/django/http/__init__.py in _assert_mutable, line 359
Python Executable: /usr/bin/python
Python Version: 2.6.6
Python Path:
['/home/user1/djangoblog',
'/usr/lib/python2.6',
'/usr/lib/python2.6/plat-linux2',
'/usr/lib/python2.6/lib-tk',
'/usr/lib/python2.6/lib-old',
'/usr/lib/python2.6/lib-dynload',
'/usr/local/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages/gst-0.10',
'/usr/lib/pymodules/python2.6',
'/usr/lib/pymodules/python2.6/gtk-2.0']
推荐答案
如果你需要在保存之前对数据做一些事情,只需创建一个像这样的函数:
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
您只需要创建一个名为 **clean_***nameofdata* 的函数,其中 nameofdata 是字段的名称,因此如果要修改密码字段,您需要:
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):
如果需要修改密码重复
def clean_passwordrepeat(self):
所以在里面,只需加密您的密码并返回加密的密码.
So inside there, just encrypt your password and return the encrypted one.
我的意思是:
def clean_password(self):
data = self.cleaned_data['password']
# encrypt stuff
return data
所以当您验证表单时,密码将被加密.
so when you valid the form, the password would be encrypted.
这篇关于如何在保存之前更改 Django 表单字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!