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']
的值?
错误:
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']
答案 0 :(得分:37)
如果您需要在保存之前对数据执行某些操作,只需创建一个类似的函数:
def clean_nameofdata(self):
data = self.cleaned_data['nameofdata']
# do some stuff
return data
您只需创建一个名为** clean _ *** nameofdata *的函数,其中 nameofdata 是该字段的名称,因此如果您想修改密码字段,则需要:
def clean_password(self):
如果您需要修改 passwordrepeat
def clean_passwordrepeat(self):
所以在那里,只需加密密码并返回加密密码。
我的意思是:
def clean_password(self):
data = self.cleaned_data['password']
# encrypt stuff
return data
因此,当您对表单有效时,密码将被加密。
答案 1 :(得分:10)
请参阅save()
方法的文档
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()
答案 2 :(得分:5)
覆盖_clean
个方法,然后添加your checks in them。您可以从那里修改cleaned_data
。
E.g:
def clean_password(self):
new1 = self.cleaned_data['password']
return new1
表单中的每个字段都有一个由Django自动创建的field_name_clean()
方法。执行form.is_valid()
时会调用此方法。
答案 3 :(得分:5)
如果您需要从POST填写表单,更改任何表单字段值并再次呈现表单,您将遇到问题。 这是解决方案:
class StudentSignUpForm(forms.Form):
step = forms.IntegerField()
def set_step(self, step):
data = self.data.copy()
data['step'] = step
self.data = data
然后:
form = StudentSignUpForm(request.POST)
if form.is_valid() and something():
form.set_step(2)
return render_to_string('form.html', {'form': form})
答案 4 :(得分:0)
以前的解决方案存在的问题是,如果验证失败,它将无法运行。为了避免验证,您可以使用实例:
instance = form.instance
instance.user = request.user
instance.save()
但请注意,这不会检查is_valid()
。如果要这样做,可以使用新值实例化表单:
# NOT TESTED, NOT SURE IF THIS WORKS...
form = MyForm(instance=instance)
if form.is_valid():
form.save()