How To Create A Custom User Model In Django

Let’s discuss some stuff about creating a custom user model in Django.

The traditional user model in django allows you to login to a website by using

username & password.

Although we are more feasible to login by using email address / mobile rather than an username.

For that we have to create our custom(desired) user model for authentication purpose.

In this project we are creating a model to login by using user’s mobile number.

Let’s write some code to achieve our objective 😊 .

Create an app in your project Ex : (my_app)

In models.py of your app write the following code below.

Import some authentication packages in django

They are AbstractBaseUser & BaseUser Manager

from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager

Create a class (User) for storing various fields like mobile,username,email etc., and the required fields are mandatory.

USERNAME_FIELD decides which field you want to use for login

# Class for creating our desired  fields
class User(AbstractBaseUser):
    mobile          = models.CharField(max_length=40,unique=True)
    email           = models.EmailField(verbose_name="email",max_length=60,unique=True)
    username        = models.CharField(max_length=30,unique=True)
    date_joined     = models.DateTimeField(verbose_name="date joined",auto_now_add=True)
    last_login      = models.DateTimeField(verbose_name="last login",auto_now_add=True)
    is_admin        = models.BooleanField(default=False)
    is_active       = models.BooleanField(default=True)
    is_staff        = models.BooleanField(default=False)
    is_superuser    = models.BooleanField(default=False)

    # This  USERNAME_FIELD  is the main part in this code which is used for login purpose
    USERNAME_FIELD  = 'mobile'

    # The username and password are the inbuilt fields you can also edit according to your requirements
    REQUIRED_FIELDS = ['username','email',]

    # Used to locate the above class(User manager)  for managing users
    objects = UserManager()

    # function returns the string
    def __str__(self):
        return self.email

    # decides the permission of the user
    def has_perm(self,perm,obj=None):
        return self.is_admin

    def has_module_perms(self,app_label):
        return True

Then create a UserManager class which holds two different functions for creating a normal user and a super user.

** This UserManager class is above the User class

# class to differenciate normal user and a superuser
class UserManager(BaseUserManager):
    # To create a normal user
    def create_user(self,email,mobile,username,password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not username:
            raise ValueError("Users must have an username")

        user    =   self.model(
            mobile=mobile,
            email = self.normalize_email(email),
            username = username,
            )
        user.set_password(password)
        user.save(using=self._db)
        return user

    # To create a super user,who has all permissions to  access the admin page
    def create_superuser(self,email,mobile,username,password):
        user = self.create_user(
            mobile=mobile,
            email=self.normalize_email(email),
            password = password,
            username=username,

            )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

The entire code for the custom user model is…

from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager


# class to differenciate normal user and a superuser
class UserManager(BaseUserManager):
    # To create a normal user
    def create_user(self,email,mobile,username,password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not username:
            raise ValueError("Users must have an username")

        user    =   self.model(
            mobile=mobile,
            email = self.normalize_email(email),
            username = username,
            )
        user.set_password(password)
        user.save(using=self._db)
        return user

    # To create a super user,who has all permissions to  access the admin page
    def create_superuser(self,email,mobile,username,password):
        user = self.create_user(
            mobile=mobile,
            email=self.normalize_email(email),
            password = password,
            username=username,

            )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


# Class for creating our desired  fields
class User(AbstractBaseUser):
    mobile          = models.CharField(max_length=40,unique=True)
    email           = models.EmailField(verbose_name="email",max_length=60,unique=True)
    username        = models.CharField(max_length=30,unique=True)
    date_joined     = models.DateTimeField(verbose_name="date joined",auto_now_add=True)
    last_login      = models.DateTimeField(verbose_name="last login",auto_now_add=True)
    is_admin        = models.BooleanField(default=False)
    is_active       = models.BooleanField(default=True)
    is_staff        = models.BooleanField(default=False)
    is_superuser    = models.BooleanField(default=False)

    # This  USERNAME_FIELD  is the main part in this code which is used for login purpose
    USERNAME_FIELD  = 'mobile'

    # The username and password are the inbuilt fields you can also edit according to your requirements
    REQUIRED_FIELDS = ['username','email',]

    # Used to locate the above class(User manager)  for managing users
    objects = UserManager()

    # function returns the string
    def __str__(self):
        return self.email

    # decides the permission of the user
    def has_perm(self,perm,obj=None):
        return self.is_admin

    def has_module_perms(self,app_label):
        return True


After creating model we have to replace the existing user model with our new model

In settings.py of your main project add these few lines

AUTH_USER_MODEL = ‘(your app name.modelname)’

AUTH_USER_MODEL = 'my_app.User'

Don’t forgot to add your app to the installed apps in settings.py 😊.

Make migrations by using #python manage.py makemigrations

Migrate all the data-models by using #python manage.py migrate

Now create a superuser by using #python manage.py createsuperuser

Follow the couple of steps and they look like

Run the server by using #python manage.py runserver

In your serchbar search # http://127.0.0.1:8000/admin

And now you can login into admin pannel by using mobile number & password.

Your custom user model is ready.

Thank you…

How to send timed messages using python & Twilio?

 

Twilio is a python library which helps you to send (text/multimedia) messages to your mobile.

First of all you have to register in this twilio API website https://www.twilio.com/try-twilio

Then you have to verify the receivers mobile number in your account.

After registering your twilio account they will give you

1.A TRIAL NUMBER.

2.An ACCOUNT SID.

3.An AUTH TOKEN

Also you have to install twilio in your machine using this command.

pip install twilio

# This is the simple code to send a message to mobile using twilio.

from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'AC911bd0d30df0c380d60627a53eb8f52d'
# DANGER! This is insecure. See http://twil.io/secure
auth_token = 'your_auth_token'
#Creates a client for twilio.
client = Client(account_sid, auth_token)
#This is the message part includes from and to addresses:
message = client.messages.create(
   #Actual message   body="Join Earth's mightiest heroes. Like Kevin Bacon.",
                     from_='+15017122661',  #Twilio number
                     to='+15558675310'   # recepants mobile number
                    )
print(message.sid)

To send a timed message you have to import datetime,time modules for current time and sleeping (required) time along with twilio.

from twilio.rest import Client
import time
import datetime

To return present time –>

present_time = time.time()

Also you have to enter the future time

ex: datetime.datetime(year,month,day,hours,min,sec)

Note: The time should always be in future to run your code error free.

#datetime.datetime(year,month,day,hours,min,sec)

time_sleep = datetime.datetime(2020, 7, 11, 17, 30, 20)

#change the time to future in this code

Allocated time to send your message is

# returns the (timer) time in seconds
required_time = (time_sleep.timestamp() - present_time)

function to return the time in seconds to normal time.

def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60

    return "%d:%02d:%02d" % (hour, minutes, seconds)
required_time = (time_sleep.timestamp() - present_time)

print(convert(required_time))

This is the code used to sleep your program until the timer (required_time) arrives.

time.sleep(time_sleep.timestamp() - present_time)

The actual code format is:

# import packages

from twilio.rest import Client
import time
import datetime

present_time = time.time()
time_sleep = datetime.datetime(2020, 7, 11, 17, 30, 20)

required_time = (time_sleep.timestamp() - present_time)

def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60

    return "%d:%02d:%02d" % (hour, minutes, seconds)



print(convert(required_time))

# code for sleep
time.sleep(time_sleep.timestamp() - present_time)


# Your Account Sid and Auth Token

account_sid = 'AC911bd0d30df0c380d60627a53eb8f52d'

# DANGER! This is insecure.
auth_token = 'your_auth_token'

#Creates a client for twilio.

client = Client(account_sid, auth_token)

#This is the message part includes from and to addresses:
message = client.messages.create(
    body="Hello cherry,what's going on.", #Actual message
    from_='+15017122661',  #your Twilio number it's dummy
    to='+15558675310'   # it's dummy recepants mobile number
                    )
print(message.sid)

Thank you ….

Create your own website, free on WordPress.com.Create your own website.
Start free