Send notification on new registration in Django

In this article, we explain how to configure and send notifications in Django using a signal dispatcher. We will try to create an application to send notifications, whenever a user registered. To Implement this example in your Django application follow the given steps - 

Step - 1: 

Create your Django project
  django-admin startproject send_notification

Step - 2: 

Now navigate inside your project directory -
  > cd send_notification

Step - 3: 

Now open the settings.py of your application, and configure the SMTP settings -
# Email setting configration
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_USE_TLS = True
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "your email id"
EMAIL_HOST_PASSWORD = "your password"

Step - 4: 

After navigating, create Django app -
  django-admin startapp accounts

Step - 5: 

After creating the app, create a file with the name signals.py in your apps. 
accounts/signals.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from django.conf import settings

@receiver(post_save, sender=User)
def send_email_on_registration(sender, instance, created, **kwargs):
    if created:
        subject = 'New user registered'
        message = 'A new user has registered:\n\nUsername: {}\nEmail: {}'.format(instance.username, instance.email)
        from_email = settings.DEFAULT_FROM_EMAIL
        recipient_list = [settings.EMAIL_HOST_USER]
        send_mail(subject, message, from_email, recipient_list, fail_silently=False)

post_save.connect(send_email_on_registration, sender=User)

Step - 6:

Now open the apps.py of your app and create a function same as given below - 
accounts/apps.py
from django.apps import AppConfig

class AccountsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'accounts'

    def ready(self):
        import accounts.signals

Step - 7: 

Now open views.py of your app and create a method to register a new user -
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User

def register(request):
    try:
        if request.method == "POST":
            data = {
                    "first_name":request.POST["first_name"],
                    "last_name":request.POST["last_name"],
                    "email":request.POST["email"],
                    "password":request.POST["password"],
                    "username":request.POST["email"].split('@')[0]
                }

            register = User.objects.create_user(**data)
            if register is not None:
                messages.success(request,"Registred Successfully")
                return redirect('register')
            else:
                messages.error(request,"Something went wrong")
                return redirect('register')
    except Exception as e:
        messages.error(request,e)
        return redirect('register')
    return render(request,'register.html')

Step - 8: 

Now configure the routes, create urls.py in your app - 
accounts / urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('register',views.register,name="register"),
]

Step - 9: 

This is the last step, Now we have to create an HTML form to save user data - 
templates/register.html
<form action="{% url 'register' %}" method="POST">
<h4>Register</h4>
{% csrf_token %}
<div>
<label>First Name</label>
<input type="text" name="first_name" required />
</div>
<div >
<label>Last Name</label>
<input type="text" name="last_name" required />
</div>
<div>
<label>Email</label>
<input type="email" name="email" required />
</div>
<div>
<label>Password</label>
<input type="password" name="password" required />
</div>
<div class="mb-3 text-center">
<button type="submit"> Register </button>
</div>
</form>
Now You can run your application.

Comments