profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Sunday, July 22, 2018

Django Allauth signal to trigger something

So I am still testing the waters of django and I am still like a baby swimmer with swim tires. I had some trouble in using django allauth signals to do something.
Django 2.0
Django allauth
All in a virtualenv.
So here is how you use signals trigger some action. Go to to checkout the signal allauth emits at various stages. I am interested in the signal which gets dispatched after the user signs up. I am using email+password to signup and signin.

from django.db import models
import time
from django.contrib.auth.models import User
from allauth.account.signals import user_signed_up, password_set
from django.dispatch import receiver, Signal

# Create your models here.
def employeeID(sender=User, **kwargs):
    old_username = kwargs['user']
    user = User.objects.get(username = old_username)
    user.username = str(time.time()).split('.')[0]

1-5 import modules.
8. mention the signal that we want to use.
as per the allauth documents mentioned in the this signal contains the following.
user_signed_up = Signal(providing_args=["request", "user"])
So the entire info received from the signal is passed on to the funtion at line 9 as **kwargs.
10. extract the signedup user's username.
11. query the database for the data of that user.
12. change the username to some random number.
13. save the changes to the database.

So, when we are using email+password only to signup and signin, allauth still creates a username='email ID' of the user (without the, so if i signed up with then my username will be mail.) So I thought I will give my own username and it worked.

No comments:

Post a Comment