【发布时间】:2016-12-29 06:13:44
【问题描述】:
我在 Django 中有自定义用户,所以在管理员的用户创建表单中,我们有 password 字段,它在创建时被保存,但是当我去更改现有用户并且我没有输入/更改密码字段时,但是它反映在数据库中。下面是我的代码
class ChangeClientEmployeeMasterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ChangeClientEmployeeMasterForm, self).__init__(*args, **kwargs)
self.fields['groups'].label='Roles'
if 'instance' in kwargs and hasattr(kwargs['instance'], 'client_employee_id'):
self.client_employee_id = kwargs['instance'].client_employee_id
def clean(self):
if self.cleaned_data['client_employee_type'] =='imast':
self.cleaned_data['is_superuser'] = True
else :
self.cleaned_data['is_superuser'] = False
return self.cleaned_data
def save(self, commit=True):
user = super(ChangeClientEmployeeMasterForm, self).save(commit=False)
password = self.cleaned_data["password"]
if password:
user.set_password(password)
if commit:
user.save()
return user
class Meta:
model = ClientEmployeeMaster
【问题讨论】:
-
当您尝试更改现有用户时,我猜
password字段已被现有密码填充,因此您的条件正在保存方法中执行。我建议在更新时加载表单时将密码设为空白。 -
yes.. 加载表单时密码字段为空,但仍然相同
-
您没有每个用户的 ID(在创建用户时创建)吗?如果是这样,那么每当您获取要更新的数据时,请检查特定请求是否带有现有 ID,然后只需更新其他详细信息而不是密码。
-
好的.. 我如何只更新有限的字段,因为我尝试使用 model.save(update_fields=["my_fields"])
标签: django python-3.x django-forms