因此,我一直遵循有关自定义用户模型(AbstractBaseUser)的Django文档示例。但是当我从管理站点创建用户时,它开始给我这个错误 “分配前已引用本地变量'password1'” 我下面有admin.py
from django.contrib import admin
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label= 'Password' , widget =
forms.PasswordInput)
password2 = forms.CharField(label = 'Password Confirmation', widget =
forms.PasswordInput)
class Meta:
model = CustomUser
#with my added feilds in AbstractBaseUser
fields = ('email','first_name','last_name', 'Mobile',
'Aadhar_Card', 'Address','is_supervisor','is_employee','is_driver')
def clean_password2(self):
password1 = self.cleaned_data.get(password1)
password2 = self.cleaned_data.get(password2)
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords Dont Match")
return password2
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
答案 0 :(得分:2)
您的[['FunctionDef'], ['args', 'arguments'], ['args', 'args', 'arg'], ['args', 'args', None], ['args', 'args', 'self'], ['body', 'Expr'], ['body', 'value', 'Str'], ['body', 'value', 'Like items(), but with all lowercase keys.'], ['body', 'Return'], ['body', 'value', 'GeneratorExp']]
方法确实引用了未定义的变量。您需要使用字符串:
clean_password2