我已经创建了一个自定义用户模型,如果在提交时设置了密码,则在注册页面中,浏览器不会让我保存,因为即使填写了密码也为空。在管理面板中如果要在提交时创建用户,密码框将保留为纯文本格式。我该如何解决?
# My user model
class Crescatori(AbstractBaseUser, PermissionsMixin):
""" Model Crescatori, folosit la inregistrarea utilizatorilor"""
email = models.EmailField(unique=True, null=True, db_index=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
nume = models.CharField(max_length=40)
prenume = models.CharField(max_length=50)
telefon = models.CharField(max_length=25, blank=True, null=True)
strada = models.CharField(max_length=254, blank=True, null=True)
numarul = models.CharField(max_length=5, blank=True, null=True)
judet = models.CharField(_('Judet/Sector'), max_length=128, blank=True, null=True)
tara = models.CharField(max_length=150, blank=True, null=True)
REQUIRED_FIELDS = ['nume', 'prenume', 'judet', 'tara']
USERNAME_FIELD = 'email'
objects = UserManager()
class Meta:
verbose_name = "Crescator"
verbose_name_plural = "Crescatori"
def get_short_name(self):
""" Returneaza numele mic al crescatorului"""
return self.nume
def get_full_name(self):
""" Returneaza numele complet al crescatorului"""
return '%s %s' % (self.nume, self.prenume)
def __str__(self):
return self.email
# User Manager
class UserManager(BaseUserManager):
""" Manager crescatori/useri inregistrati"""
def create_user(self, email, password, **extra_fields):
""" Functie pentru crearea utilizatorilor"""
if not email:
raise ValueError(_('Adresa de email nu poate fi necompletata'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
""" Functie pentru crearea adminilor"""
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Pentru administratori nu a fost setat is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
# My view
class RegisterView(CreateView):
""" Modul pentru crearea formularului de inregistrare"""
model = Crescatori
fields = ['nume', 'prenume', 'judet', 'tara', 'password', 'email']
template_name = 'myapp/registration.html'
success_url = reverse_lazy('login')
def form_valid(self, form):
"""Functie pentru criptarea parolei """
# Hash password before sending it to super
form.instance.password = make_password(form.instance.password)
return super().form_valid(form)
有什么我想念的吗?预先感谢。
答案 0 :(得分:0)
# your can use set_password function
user = user_form.save()
user.set_password(user.password) # create the hashed password
user.save() # then save it