保存前如何更改Django表单字段值? [英] How can I change a Django form field value before saving?

查看:211
本文介绍了保存前如何更改Django表单字段值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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):

如果您需要修改 passwordrepeat

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表单字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆