I am trying to build a custom user model in Django. My models.py looks like this:
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not username:
raise ValueError(_('The given username must be set'))
if not email:
raise ValueError(_('The given email must be set'))
email = self.normalize_email(email)
user = self.model(
username=username, email=email,
is_staff=is_staff, is_active=False,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, password=None, **extra_fields):
return self._create_user(username, email, password, False, False, **extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
user=self._create_user(username, email, password, True, True, **extra_fields)
user.is_active=True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
# Standard fields
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), _('invalid'))
])
first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
email = models.EmailField(_('email address'), max_length=255)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
# Custom fields
is_publisher = models.BooleanField(_('publisher status'), default=False)
# User manager
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
Anyway, if I create a super user using the createsuperuser command, everything works fine : the user is created, and the password is hashed properly and secured. However, if I create a user from my admin panel, the user created has his/her password completely exposed. Also the confirm password field doesn't show up, which it does in the regular user model used in Django. How can I solve this problem?
Also, yes I do have AUTH_USER_MODEL = 'myapp.User' in my settings.py.
You need a custom ModelForm and ModelAdmin for creating/ updating User model items.
def home(request): if request.method == 'POST': uf = UserForm(request.POST, prefix='user') upf = UserProfileForm(request.POST, prefix='userprofile') if uf.is_valid() * upf.is_valid(): userform = uf.save(commit=False) userform.password = make_password(uf.cleaned_data['password']) userform.save() messages.success(request, 'successful Registration', extra_tags='safe') else: uf = UserForm(prefix='user') return render_to_response('base.html', dict(userform=uf ), context_instance=RequestContext(request))
In your views.py try to use this and in forms.py try to get the password from django form. Hope this works
A form with no custom code, and direct access to password
field, writes directly on the password field. No call is made to createuser or createsuperuser , so set_password is never called (by default, a ModelForm calls save
in the model when called save
in it). Recall that writing the user password does not write a secure password (that's why createuser
and createsuperuser
call set_password
somewhere). To do that, avoid writing directly on the field but, instead, calling:
myuserinstance.set_password('new pwd')
# not this:
# myuserinstance.password = 'new pwd'
So you must use custom logic in a custom form. See the implementation for details; you will notice those forms have custom logic calling set_password and check_password . BTW default UserAdmin in Django creates a user in TWO steps: user/password/password_confirm (such password creates), and then whole user data. There's a very custom implementation for that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.