只有在Django admin中更新用户时输入密码才更新密码

时间:2016-12-29 06:13:45

标签: django python-3.x django-forms

我在Django中有自定义用户,因此在admin中的用户创建表单中我们有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

1 个答案:

答案 0 :(得分:0)

你试试这个选项,我在Django Admin 1.10中试过这个。这应该有用。

def clean(self):
    password = self.cleaned_data['password']
    if not password and password =='':
        del self.cleaned_data['password']
     #Add your extra code / statement here, if you need.
    return self.cleaned_data