0

I am asking for how to add a Signal in model User and know if that user was registred through Facebook, I mean, if an new User is created in Django with Facebook I want to catch this event and save a new Customer model. I believe that could be something like That:

# SIGNALS AND LISTENERS
from django.contrib.auth.models import User
from django.db.models import signals
from django.dispatch import dispatcher
form customers.model import Customer

# User
def user_post_save(sender, instance, signal, *args, **kwargs):
    # Creates user profile
    if user # <- SOMETHGING LIKE IF USER IS LOGGED IN WITH FACEBOOK...
        customer = Customer.objects.get_or_create(owner=instance)

dispatcher.connect(user_post_save, signal=signals.post_save, sender=User)

In the comment you can see what I need. Thanks for your help.

Pablo Alejandro
  • 591
  • 2
  • 10
  • 19

2 Answers2

1

Django provides of built-in signals : pre_save,pre_init...

use this like:

def password_change_signal(sender, instance, **kwargs):
    try:
        user = User.objects.get(username=instance.username)
        if not hasattr(user, 'userprofile'):
            print 'has no profile'
            return
        if not user.password == instance.password:
            print 'setting vals'
            profile = user.get_profile()
            profile.force_password_change = False
            profile.save()
    except User.DoesNotExist:
        pass

signals.pre_save.connect(password_change_signal, sender=User,dispatch_uid='members.models.UserProfile') 

mtt2p
  • 1,818
  • 1
  • 15
  • 22
0

According to this SO POST, You can use post_save.connect() to save customer object whenever a user is created. Please note that I have pasted and edited code in aforementioned post according to your requirements.

from django.db.models.signals import post_save
from .models import Customer
from django.contrib.auth.models import User

def create_customer(sender, **kwargs):
    user = kwargs["instance"]
    if kwargs["created"]:
        customer = user.models.Customer()
        customer.setUser(sender)
        customer.save()

post_save.connect(create_customer, sender=User)
Community
  • 1
  • 1
cutteeth
  • 2,148
  • 3
  • 25
  • 45