In Django documentation, it says that it hashes the password but is not saving it, so I have to save it, as I did. If I create a superuser then everything is ok, but when I try to create a user account, the password gets saved unhashed into the database. I try to use make_password, but that doesn't work either, I get the same result. Do you have any idea?
models.py
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from datetime import datetime
from django.core.validators import MinLengthValidator
from .CHOICES import *
from django.utils.translation import gettext_lazy as _
from django.db import models
# Create your models here.
country_choice = COUNTRY_CHOICE
class CustomAccountManager(BaseUserManager):
Here is the custom user model.
def create_superuser(self, email, username, first_name, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError('Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError('Superuser must be assigned to is_superuser=True.')
return self.create_user(email, username, first_name, password, **other_fields)
Here is the user model.
def create_user(self, email, username, first_name, password, **other_fields):
if not email:
raise ValueError(_('You must provide an email address'))
email = self.normalize_email(email)
user = self.model(email=email, username=username,
first_name=first_name, **other_fields)
user.set_password(password)
# user.make_password(self.request.data[password])
user.save()
return user
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
username = models.CharField(max_length=50, validators=[MinLengthValidator(8)], unique=True)
first_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False)
middle_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=False)
# date_of_birth = models.DateField(blank=True)
# month = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(12)], blank=False)
# year = models.IntegerField(validators=[MinValueValidator(1942), MaxValueValidator(2017)], blank=False)
# gender model
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
gender = models.CharField(max_length=1, choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], blank=False)
country = models.CharField(max_length=2, choices=COUNTRY_CHOICE, blank=False)
datetime = models.DateTimeField(default=datetime.now())
objects = CustomAccountManager()
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name']
def __str__(self):
return self.username
Then I have forms.py
from django.forms import ModelForm, TextInput, EmailInput, PasswordInput
from .models import NewUser
class Person(ModelForm):
class Meta:
model = NewUser
fields = ["username", "email", "first_name", "middle_name", "last_name",
"gender", "country", "password"]
And views.py
def register(request):
if request.user.is_authenticated:
return redirect('profiles')
else:
if request.method == 'POST':
form_one = Person(request.POST)
Person()
if form_one.is_valid():
form_one.save()
username = form_one.cleaned_data.get("username")
messages.success(request, f"Account created for {username}!")
return redirect("login_user")
else:
form_one = Person()
return render(request, "accounts/register.html", {"form_one": form_one})
I don't understand what's wrong. Sorry for anything that might upset you, I'm new with Django, and I can't say I'm a python expert, but I try my best. Thank you very much in advance! Github link to the whole project https://github.com/RazzTazz28/Django-Atlas.
CodePudding user response:
you have to save the user after set_password. Set password only creates a hashed pasword, you have to save it
if (request.method == 'POST'):
username = request.POST.get('username')
password = request.POST.get('password')
user = User.objects.create_user(
email=email,
name=username,
password=password,
)
user.set_password(password)
user.save()