如何在保存之前更改 Django 表单字段值?

问题描述 投票:0回答:6
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']
python django forms model save
6个回答
57
投票

如果您需要在保存之前对数据执行某些操作,只需创建一个如下函数:

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

您所需要做的就是创建一个名为 **clean_***nameofdata* 的函数,其中 nameofdata 是字段的名称,因此如果您想修改密码字段,您需要:

def clean_password(self):

如果需要修改密码重复

def clean_passwordrepeat(self):

所以在里面,只需加密您的密码并返回加密的密码即可。

我的意思是:

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

因此,当您验证表单时,密码将被加密。


22
投票

请参阅

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

9
投票

如果您需要从 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})

6
投票

覆盖

_clean
方法并将 您的支票放入其中。您可以从那里修改
cleaned_data

例如:

def clean_password(self):
    new1 = self.cleaned_data['password']
    return new1

表单中的每个字段都会有一个由 Django 自动创建的

field_name_clean()
方法。当您执行
form.is_valid()
时会调用此方法。


3
投票

浏览次数:

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.my_field = 'value'
        obj.save()

表格中:

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

0
投票

最初的问题是“在保存之前修改/更新表单字段值”。上面的一些方法好像是保存后才用的。 此参考可能有助于解决此 QueryDict 实例是不可变的。您可以尝试以下方法

if request.method == 'POST': userf = UsersModelForm(request.POST) ... data = request.POST.copy() # remember old state _mutable = data._mutable # set to mutable data._mutable = True data['password'] = password data['passwordrepeat'] = passwordrepeat # set mutable flag back data._mutable = _mutable userf = UsersModelForm(data) if userf.is_valid(): userf.save()
    
© www.soinside.com 2019 - 2024. All rights reserved.