djangodjango-modelsdjango-viewsdjango-custom-userdjango-modeladmin

How to register a normal user in django from front end using custom user model?


# Custom User Model Code
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class MyUserManager(BaseUserManager):
    def create_user(self, email, favorite_color, password=None):
        """
        Creates and saves a User with the given email, favorite color
         and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            favorite_color=favorite_color,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, favorite_color, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            favorite_color=favorite_color,
        )
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    favorite_color = models.CharField(max_length=50)
    bio = models.TextField(null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['favorite_color']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin



# Templates Code as I want to use my own template instead of using forms.py
<html>
    <head>
        <title>
            CustomUserModel
        </title>
    </head>
    <body>
        <form method="POST" action="register">
            {% csrf_token %}
            Email : <input type="email" name="email"> <br>
            Password : <input type="password" name="password"> <br>
            Favourite Colour : <input type="text" name='colour'><b>
            Bio : <textarea name='bio'></textarea>    <br>
            <button type="submit">SUBMIT</button>
        </form>
    </body>
</html>



# Views Code
def register(request):
    if request.method == 'POST':
        email = request.POST['email']
        passwd = request.POST['password']
        clr = request.POST['colour']
        bio = request.POST['bio']
        user = MyUser(email=email,password=passwd,favorite_color=clr,bio=bio)
        user.save()
        return redirect('/')

    return render(request,'home.html')   

The main problem I am facing while registering a user from front end is that the password is saving into the data base in clear text-format, it is not getting hashed but while I am registering an user from the django admin panel the password is getting saved in proper hashed format. Why is it so ? What are the changes I need to perform in views.py to store the password in proper hash format in database?

I don't want to use django forms. Please help


Solution

  • You are saving not hashed password.

    Django User have set_password() method which take cares of hashing.

    def register(request):
        if request.method == 'POST':
            user = MyUser()
            user.set_password(request.POST['password'])
            user.email = request.POST['email']
            user.favorite_color = request.POST['colour']
            user.bio = request.POST['bio']
            user.save()
    
            return redirect('/')
    
         return render(request,'home.html')
    

    Note: You don't have any validation here. You should consider about writing some.