def ready(self): from shuup.core.models import CompanyContact from .notify_events import send_company_activated_first_time_notification from .signals import handle_user_activation user_activated.connect(handle_user_activation) if not hasattr(django.conf.settings, "ACCOUNT_ACTIVATION_DAYS"): # Patch settings to include ACCOUNT_ACTIVATION_DAYS; # it's a setting owned by `django-registration-redux`, # but not set to a default value. If it's not set, a crash # will occur when attempting to create an account, so # for convenience, we're doing what `django-registration-redux` # didn't wanna. django.conf.settings.ACCOUNT_ACTIVATION_DAYS = 7 if not hasattr(django.conf.settings, "REGISTRATION_AUTO_LOGIN"): # By default, Django-Registration considers this False, but # we override it to True. unless otherwise set by the user. django.conf.settings.REGISTRATION_AUTO_LOGIN = True if not hasattr(django.conf.settings, "REGISTRATION_EMAIL_HTML"): # We only provide txt templates out of the box, so default to # false for HTML mails. django.conf.settings.REGISTRATION_EMAIL_HTML = False company_contact_activated.connect( send_company_activated_first_time_notification, sender=CompanyContact, )
def ready(self): from wshop.core.models import CompanyContact from .notify_events import send_company_activated_first_time_notification from .signals import handle_user_activation user_activated.connect(handle_user_activation) if not hasattr(django.conf.settings, "ACCOUNT_ACTIVATION_DAYS"): # Patch settings to include ACCOUNT_ACTIVATION_DAYS; # it's a setting owned by `django-registration-redux`, # but not set to a default value. If it's not set, a crash # will occur when attempting to create an account, so # for convenience, we're doing what `django-registration-redux` # didn't wanna. django.conf.settings.ACCOUNT_ACTIVATION_DAYS = 7 if not hasattr(django.conf.settings, "REGISTRATION_AUTO_LOGIN"): # By default, Django-Registration considers this False, but # we override it to True. unless otherwise set by the user. django.conf.settings.REGISTRATION_AUTO_LOGIN = True if not hasattr(django.conf.settings, "REGISTRATION_EMAIL_HTML"): # We only provide txt templates out of the box, so default to # false for HTML mails. django.conf.settings.REGISTRATION_EMAIL_HTML = False company_contact_activated.connect( send_company_activated_first_time_notification, sender=CompanyContact, )
def activate(): from django.db.models.signals import post_delete from django.db.models.signals import post_save from django.contrib.auth.models import Group from django.contrib.auth.models import User post_save.connect(dispatch_post_save_signal, sender=User) post_save.connect(dispatch_post_save_signal, sender=Group) post_delete.connect(dispatch_delete_signal, sender=User) post_delete.connect(dispatch_delete_signal, sender=Group) try: from registration.signals import user_activated from registration.signals import user_registered user_activated.connect(dispatch_user_activated) user_registered.connect(dispatch_user_registered) except ImportError: pass
def ready(self): if not hasattr(django.conf.settings, "ACCOUNT_ACTIVATION_DAYS"): # Patch settings to include ACCOUNT_ACTIVATION_DAYS; # it's a setting owned by `django-registration-redux`, # but not set to a default value. If it's not set, a crash # will occur when attempting to create an account, so # for convenience, we're doing what `django-registration-redux` # didn't wanna. django.conf.settings.ACCOUNT_ACTIVATION_DAYS = 7 if not hasattr(django.conf.settings, "REGISTRATION_AUTO_LOGIN"): # By default, Django-Registration considers this False, but # we override it to True. unless otherwise set by the user. django.conf.settings.REGISTRATION_AUTO_LOGIN = True # connect signal here since the setting value has changed user_activated.connect(login_user) if not hasattr(django.conf.settings, "REGISTRATION_EMAIL_HTML"): # We only provide txt templates out of the box, so default to # false for HTML mails. django.conf.settings.REGISTRATION_EMAIL_HTML = False
def unset_cookie(sender, request, user, **kwargs): request.delete_cookie("__ac") user_logged_out.connect(unset_cookie) def confirm_email_contact(sender, user, **kwargs): if not user.is_active: return False email = user.email contact, _ = EmailContact.objects.get_or_create(email=email, user=user) contact.confirm() user_activated.connect(confirm_email_contact) def process_deferrals(sender, contact, **kwargs): if not contact.confirmed: return False if not contact.user.is_active: return False deferrals = DeferredMessage.objects.filter(contact=contact) for deferral in deferrals: message = deferral.message.encode("utf-8") msg = email.message_from_string(message) gateway.process(msg) deferral.delete()
class AgentProfile(models.Model): phone = models.CharField(max_length=60, blank=True, null=True) first_name = models.CharField(max_length=60, blank=True, null=True) last_name = models.CharField(max_length=60, blank=True, null=True) avatar = models.ImageField(upload_to='avatars/', default='avatars/no-img.png') title = models.CharField(max_length=120, blank=True, null=True) user = models.OneToOneField(Agent, related_name='profile', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('agent:detail', kwargs={'email': self.user.email}) # Activation signal def check_domain(sender, user, request, **kwargs): domain, created = Domain.objects.get_or_create( name=user.email.split('@')[1]) if created: user.is_owner = True user.domain = domain user.save() from registration.signals import user_activated user_activated.connect(check_domain, dispatch_uid='registration.signals.user_activated')
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from registration.signals import user_registered, user_activated from datawinners.accountmanagement.post_registration_events import ngo_user_created from datawinners.accountmanagement.post_activation_events import initialize_organization user_registered.connect(ngo_user_created) user_activated.connect(initialize_organization)
from django.contrib.auth.models import User from django.db.models.signals import pre_delete from registration.signals import user_activated from marketing.tasks import create_mailchimp_recipient, delete_mailchimp_recipient def delete_mailchimp_email(sender, instance, **kwargs): if instance.pk: old_email = User.objects.get(pk=instance.pk).email delete_mailchimp_recipient.delay(old_email) def create_mailchimp_email(sender, **kwargs): if 'user' in kwargs: instance = kwargs['user'] elif 'instance' in kwargs: instance = kwargs['instance'] if instance.is_active: create_mailchimp_recipient.delay(instance.pk) user_activated.connect(create_mailchimp_email) pre_delete.connect(delete_mailchimp_email, sender=User)
def link_to_user(self, user, save=True): self._name = '' self._email = '' self._kind = None self.user = user if save: self.save() def __unicode__(self): base = self.email base += "(%s)" % self.user.username if self.user else "" return "%s [%s]" % (base, self.receive) # When a user's been registered, associate his subscriptions with him if he # already has some. Also, activate any subscriptions that haven't yet been # activated, since we know that his email is correct. We shouldn't associate # (or confirm) subscribers before user activation, since they might not really # have the email address they signed up with. def setup_subscribers(sender, user, **kwargs): profile = user.get_profile() # associate subscribers with the same email address here Subscriber.objects.filter(_email=user.email).update( _name='', _email='', _kind=None, user=profile) # confirm linked subscribers Subscriber.objects.filter(user=profile).update(is_confirmed=True) user_activated.connect(setup_subscribers)
from registration.signals import user_activated from django.contrib.auth.models import Permission def perms_on_activation(sender, user, request, **kwargs): #login to admin site user.is_staff = True #blogs user.user_permissions.add(Permission.objects.get(codename='add_blog')) user.user_permissions.add(Permission.objects.get(codename='change_blog')) user.user_permissions.add(Permission.objects.get(codename='delete_blog')) #events user.user_permissions.add(Permission.objects.get(codename='add_event')) user.user_permissions.add(Permission.objects.get(codename='change_event')) user.user_permissions.add(Permission.objects.get(codename='delete_event')) #user profile user.user_permissions.add(Permission.objects.get(codename='add_userprofile')) user.user_permissions.add(Permission.objects.get(codename='change_userprofile')) user.user_permissions.add(Permission.objects.get(codename='delete_userprofile')) user.save() user_activated.connect(perms_on_activation)
def create_user_profile_registered(sender, user, request, **kwargs): UserProfile.objects.get_or_create(user=user) logger.info('user profile for user %s has been created after registration %s' % ( user, datetime.now())) mail_admins('New User Registered', 'User %s registered at %s' % (user, datetime.now())) logger.info('email has been sent to admins informing of registration of user %s' % user) user_registered.connect(create_user_profile_registered, dispatch_uid="registered") def register_handler(request, sender, user, **kwargs): messages.success(request, 'Thank you! Your account has been activated.') user_activated.connect(register_handler, dispatch_uid='activated') # check if user has a catch all project and create one if not def create_catch_all_project( sender, user, request, **kwargs ): if user.get_profile().catch_all_project is None: project = Project.objects.create( name="Catch-All Project", is_catch_all=True ) project.set_owner( user ) user.get_profile().catch_all_project = project user.get_profile().save() messages.success(request, "If you don't want to fill your profile out now, you can go to the <a href='/'>homepage</a>.", extra_tags='safe', fail_silently=True) # needed to avoid MessageFailure when running tests # create catch all project for user if none exists
derived_from = CharField(max_length=64, blank=True) creator = models.ForeignKey(User) status = IntegerField(null=True, default=1) author = CharField(max_length=100, blank=True, default="") editor = CharField(max_length=100, blank=True, default="") licensor = CharField(max_length=100, blank=True, default="") maintainer = CharField(max_length=100, blank=True, default="") translator = CharField(max_length=100, blank=True, default="") coeditor = CharField(max_length=100, blank=True, default="") def to_dict(self): material = dict() material['id'] = self.id material['material_id'] = self.material_id material['material_type'] = int(self.material_type) material['text'] = self.text material['version'] = self.version material['title'] = self.title material['description'] = self.description material['categories'] = self.categories material['status'] = self.status material['modified'] = self.modified if self.author: material['author'] = self.author return material user_activated.connect(user_activated_callback, dispatch_uid="ACTIVE_USER")
from django.contrib import admin from models import User, UserProfile from django.contrib.auth.signals import user_logged_in from django.db.models import signals # 3rd-party ``registration`` app: connect up the signals import views from registration.signals import user_registered, user_activated class UserProfileAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'is_validated', 'affiliation', 'country', 'reputation', 'bio', 'uri', 'openid', 'contactable_via_site', 'allow_user_to_email') list_display_links = ('user',) list_per_page = 1000 ordering = ('user',) admin.site.register(UserProfile, UserProfileAdmin) # Hook up the signals here. Doing it in models.py results in circular imports. user_registered.connect(views.create_new_account) user_activated.connect(views.account_activation) user_logged_in.connect(views.user_logged_in) # Create a ``UserProfile`` for every user signals.post_save.connect(views.create_new_account, User)
'site': Site.objects.get_current()})) email = EmailMessage(subject='%s %s' % (settings.EMAIL_SUBJECT_PREFIX, _('Welcome')), body=text, from_email=settings.DEFAULT_FROM_EMAIL, to=[user.email], headers={'Reply-To': settings.DEFAULT_SUPPORT_EMAIL}) email.send() log.info('Welcome mail sent to user: %r' % user) except Exception: log.exception('Error sending welcome mail to user: %r' % user) # we make here all errors silence to the user, but we log them from registration.signals import user_activated user_activated.connect(send_welcome_email, dispatch_uid='send_welcome_email_after_account_activation') from .models import UserProfile def too_few_credits_check(sender, instance, **kwargs): ''' This function sends mail to user if the credits level goes down. Tested only as pre_save signal for UserProfile model! If this function is called as signal, `instance`.credits is unsaved yet, and can be integer or ExpressionNode (django F query). ''' log = logging.getLogger('webscanner.account.send_lowcredits_email')
notification.send([supporter], "wishlist_message", { 'work': work, 'msg': msg }, True, sender) from regluit.core.tasks import emit_notifications emit_notifications.delay() supporter_message.connect(notify_supporter_message) def notify_join_library(sender, created, instance, **kwargs): if created: notification.send((instance.user, instance.library.user), "library_join", { 'library': instance.library, 'user': instance.user, }) post_save.connect(notify_join_library, sender=LibraryUser) from registration.signals import user_activated def ml_subscribe(user, request, **kwargs): user.profile.ml_subscribe() user_activated.connect(ml_subscribe)
application = models.ForeignKey(Application) user_profile = models.ForeignKey(UserProfile) token = models.CharField(max_length=50) def __unicode__(self): return "%s : %s" % (self.application, self.token) class AccessToken(BaseAppModel): user_profile = models.ForeignKey(UserProfile) application = models.ForeignKey(Application) token = models.CharField(max_length=50) def __unicode__(self): return "%s : %s" % (self.user_profile, self.token) def create_first_application(sender, **kwargs): user_profile = kwargs["user"].get_profile() if not Application.objects.filter(user_profile=user_profile).count(): client_id = "".join([random.choice(CLIENT_PARAMS_SPACE) \ for ii in range(0, 50)]) client_secret = "".join([random.choice(CLIENT_PARAMS_SPACE) \ for ii in range(0, 50)]) Application.objects.create(user_profile=user_profile, client_id=client_id, client_secret=client_secret) user_activated.connect(create_first_application)
from registration.signals import user_activated from medialibrary.models import MediaLibrary def registration_user_activated_signal(sender, **kwargs): """ receive signal from django-registration for when a new user has activated their account. Upon activation you will want to create a default UserProfile (model in django-profiles app). """ if 'user' in kwargs: user = kwargs['user'] if not MediaLibrary.objects.filter(user=user).count(): pml = MediaLibrary(user=user) pml.save() user_activated.connect(registration_user_activated_signal)
def send_admin_awaiting_approval_email(user, request, **kwargs): # Bit more controlled than just emailing all superusers for admin in models.Profile.admins(): # Check we've ever emailed them before and if so, if cooldown has passed. if admin.last_emailed is None or admin.last_emailed + settings.EMAIL_COOLDOWN <= timezone.now(): context = { 'request': request, 'link_suffix': reverse("admin:RIGS_profile_changelist") + '?is_approved__exact=0', 'number_of_users': models.Profile.users_awaiting_approval_count(), 'to_name': admin.first_name } email = EmailMultiAlternatives( "%s new users awaiting approval on RIGS" % (context['number_of_users']), get_template("RIGS/admin_awaiting_approval.txt").render(context), to=[admin.email], reply_to=[user.email], ) css = staticfiles_storage.path('css/email.css') html = Premailer(get_template("RIGS/admin_awaiting_approval.html").render(context), external_styles=css).transform() email.attach_alternative(html, 'text/html') email.send() # Update last sent admin.last_emailed = timezone.now() admin.save() user_activated.connect(send_admin_awaiting_approval_email)
from techblog import signal_listeners from registration.signals import user_activated from django.contrib.comments.signals import comment_was_posted user_activated.connect(signal_listeners.on_user_activate) comment_was_posted.connect(signal_listeners.on_article_comment)
summ = 0.0 ) group = Group.objects.get(name='clients') group.user_set.add(user) def payment(sender, **kwargs): if kwargs.get('InvId'): bid = Bid.objects.get(pk=kwargs.get('InvId')) balance = bid.user.balance balance.summ += bid.summ bid.status = True bid.save() balance.save() result_received.connect(payment) user_activated.connect(add2group) class DashboardView(ListView): template_name = 'dashboard.html' context_object_name = 'tasks' title = u'Все задачи' active = 'all' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): """ Декорируем диспетчер функцией login_required, чтобы запретить просмотр отображения неавторизованными пользователями """ return super(DashboardView, self).dispatch(request, *args, **kwargs)
translation.get_language()) def notify_ll_on_activation(sender, user, request, **kwargs): LOG.info("notify_ll_on_activation triggered {0}, {1}".format(sender, user)) # TODO: session var or UserProfile field to record the fact that LL # have been notified user_profile = UserProfile.objects.get(user__pk=user.id) # TODO -- poss. need to check type of user and treat accordingly? notify_ll_of_new_user() # There's a bug in registration that causes the user_activated signal to be # sent twice, so these handlers need to cope with being called more than once # for the same event. # (NB. Using a unique dispatch_uid only prevents the handler from being # registered more than once; the signal will still be received twice.) # connect the signal to the set default good cause function user_activated.connect(activate_set_default_good_cause) # connect the signal to order a new card when a user activates their account user_activated.connect(order_new_card_on_activation) # connect the signal to notify Loyalty Lab when user activates user_activated.connect(notify_ll_on_activation, dispatch_uid='icare4u_notify_ll_new_user')
class AuthorizationCode(BaseAppModel): application = models.ForeignKey(Application) user_profile = models.ForeignKey(UserProfile) token = models.CharField(max_length=50) def __unicode__(self): return "%s : %s" % (self.application, self.token) class AccessToken(BaseAppModel): user_profile = models.ForeignKey(UserProfile) application = models.ForeignKey(Application) token = models.CharField(max_length=50) def __unicode__(self): return "%s : %s" % (self.user_profile, self.token) def create_first_application(sender, **kwargs): user_profile = kwargs["user"].get_profile() if not Application.objects.filter(user_profile=user_profile).count(): client_id = "".join([random.choice(CLIENT_PARAMS_SPACE) \ for ii in range(0, 50)]) client_secret = "".join([random.choice(CLIENT_PARAMS_SPACE) \ for ii in range(0, 50)]) Application.objects.create(user_profile=user_profile, client_id=client_id, client_secret=client_secret) user_activated.connect(create_first_application)
UserProfile.objects.create(user=user, self_registered=True, title=request.POST['title'].strip(), institution=request.POST['institution'].strip(), referred_by=request.POST['referred_by'], user_story=request.POST['user_story']) def user_activated_callback(sender, user, request, **kwargs): # add this user to the guest sandbox by default sandbox = get_guest_sandbox() sandbox.group.user_set.add(user) user_registered.connect(user_registered_callback) user_activated.connect(user_activated_callback) class CourseInvitation(models.Model): email = models.EmailField() course = models.ForeignKey(Course) uuid = UUIDField(default=uuid.uuid4, editable=False) invited_by = models.ForeignKey(User, related_name='invited_by') invited_at = models.DateTimeField(auto_now_add=True) accepted_at = models.DateTimeField(null=True) accepted_user = models.ForeignKey(User, null=True) def accepted(self): return self.accepted_at is not None
# http://{{ site.domain }}{% url registration_activate activation_key %} # {% url admin:metadata_layerext_changelist %} # get admin url2A site = get_current_site() registration = user.registrationprofile_set.all()[0] user_url = urlresolvers.reverse( 'admin:registration_registrationprofile_change', args=(registration.pk, )) mail_admins( 'Account pending', '%s is waiting for approval. Active user at http://%s%s' % (user.username, site, user_url)) user_activated.connect(deactivate) def approve(instance, sender, created, **kwargs): if instance.approved and not instance.user.is_active: instance.user.is_active = True instance.user.save() ctx_dict = {'site': get_current_site()} subject = render_to_string('registration/approval_email_subject.txt', ctx_dict) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string('registration/approval_email.txt', ctx_dict)
DEFAULT_USER_ID = 1 TAG_MAX_LEN = 32 HOST_CHOICES = (('ig', 'imgur'),) # keys are ideally 2 letters, # cannot start with a number # signals def createUserScore(sender, **kwargs): u = kwargs.get('user') if u is not None: us = UserScore(user=u) us.save() else: print "user_activated signal caught, but UserScore not created" user_activated.connect(createUserScore) # catch django_registration's # user_activated signal and create # necessary objects for user # utility functions def group(queryset, group, intermediate=False): if intermediate: for obj in queryset: obj.gif.group = group else: for obj in queryset: obj.group = group return queryset
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from registration.signals import user_registered, user_activated from datawinners.accountmanagement.post_registration_events import ngo_user_created from datawinners.accountmanagement.post_activation_events import create_org_database user_registered.connect(ngo_user_created) user_activated.connect(create_org_database)
} # needed by guardian ANONYMOUS_USER_ID = -1 from registration.signals import user_activated from django.contrib.auth import login def login_on_activation(sender, user, request, **kwargs): set_default_form_builder(user) user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) user_activated.connect(login_on_activation) EMAIL_BACKEND = os.environ.get( 'EMAIL_BACKEND', 'django.core.mail.backends.filebased.EmailBackend') if EMAIL_BACKEND == 'django.core.mail.backends.filebased.EmailBackend': EMAIL_FILE_PATH = os.environ.get('EMAIL_FILE_PATH', os.path.join(BASE_DIR, 'emails')) if not os.path.isdir(EMAIL_FILE_PATH): os.mkdir(EMAIL_FILE_PATH) if os.environ.get('DEFAULT_FROM_EMAIL'): DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL') SERVER_EMAIL = DEFAULT_FROM_EMAIL if os.environ.get('AWS_ACCESS_KEY_ID'):
secret = libopencore.auth.get_secret(settings.OPENCORE_SECRET_FILENAME) val = libopencore.auth.generate_cookie_value(user.username, secret) request.set_cookie("__ac", val) user_logged_in.connect(set_cookie) def unset_cookie(sender, request, user, **kwargs): request.delete_cookie("__ac") user_logged_out.connect(unset_cookie) def confirm_email_contact(sender, user, **kwargs): if not user.is_active: return False email = user.email contact, _ = EmailContact.objects.get_or_create(email=email, user=user) contact.confirm() user_activated.connect(confirm_email_contact) def process_deferrals(sender, contact, **kwargs): if not contact.confirmed: return False if not contact.user.is_active: return False deferrals = DeferredMessage.objects.filter(contact=contact) for deferral in deferrals: message = deferral.message.encode("utf-8") msg = email.message_from_string(message) gateway.process(msg) deferral.delete() contact_confirmed.connect(process_deferrals) def log_in_user(sender, user, request, **kwargs):
(BRONZE_MTYPE, "Bronze"), (SILVER_MTYPE, "Silver"), (GOLD_MTYPE, "Gold"), ) member = models.BooleanField(default=False) membershipType = models.IntegerField(choices=MEMBERSHIP_TYPES, default=NONE_MTYPE) membershipExpiry = models.DateTimeField(null=True) # specific per game customWordwallsStyle = models.CharField(max_length=1000, blank = True) wordwallsSaveListSize = models.IntegerField(default = 0) def __unicode__(self): return "Profile for " + self.user.username def userActivatedHandler(sender, **kwargs): for key in kwargs: if key == 'user': #print "User: "******"activated!" profile = AerolithProfile() profile.user = kwargs[key] profile.save() user_activated.connect(userActivatedHandler) # specific tables
UserProfile.objects.create(user=user, self_registered=True, title=request.POST['title'].strip(), institution=request.POST['institution'].strip(), referred_by=request.POST['referred_by'], user_story=request.POST['user_story']) def user_activated_callback(sender, user, request, **kwargs): # add this user to the guest sandbox by default sandbox = get_guest_sandbox() sandbox.group.user_set.add(user) user_registered.connect(user_registered_callback) user_activated.connect(user_activated_callback) class CourseInvitation(models.Model): email = models.EmailField() course = models.ForeignKey(Course, on_delete=models.CASCADE) uuid = UUIDField(default=uuid.uuid4, editable=False) invited_by = models.ForeignKey(User, related_name='invited_by', on_delete=models.CASCADE) invited_at = models.DateTimeField(auto_now_add=True) accepted_at = models.DateTimeField(null=True) accepted_user = models.ForeignKey(User, null=True,
user = User.objects.get(username=kwargs["user"]) user.is_active = False user.save() # http://{{ site.domain }}{% url registration_activate activation_key %} # {% url admin:metadata_layerext_changelist %} # get admin url2A site = get_current_site() registration = user.registrationprofile_set.all()[0] user_url = urlresolvers.reverse("admin:registration_registrationprofile_change", args=(registration.pk,)) mail_admins( "Account pending", "%s is waiting for approval. Active user at http://%s%s" % (user.username, site, user_url) ) user_activated.connect(deactivate) def approve(instance, sender, created, **kwargs): if instance.approved and not instance.user.is_active: instance.user.is_active = True instance.user.save() ctx_dict = {"site": get_current_site()} subject = render_to_string("registration/approval_email_subject.txt", ctx_dict) # Email subject *must not* contain newlines subject = "".join(subject.splitlines()) message = render_to_string("registration/approval_email.txt", ctx_dict) instance.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
from django.dispatch import receiver from guardian.shortcuts import assign_perm from django.db.models.signals import post_save from django.contrib.auth.signals import user_logged_in from registration.signals import user_activated def create_user_profile(sender, user, request, **kwargs): user_profile = UserProfile.objects.get_or_create(user=user)[0] from guardian.shortcuts import assign_perm assign_perm('change_userprofile', user, user_profile) assign_perm('delete_userprofile', user, user_profile) assign_perm('change_user', user, user) def check_userprofile_details(sender, request, user, **kwargs): if not user.first_name: request.session['no_name'] = True topic_list = TopicFollow.objects.filter(user=user) if not topic_list: request.session['no_topic'] = True def create_project_permission(sender, instance, created, **kwargs): if created: assign_perm('change_project', instance.user, instance) assign_perm('delete_project', instance.user, instance) user_activated.connect(create_user_profile) user_logged_in.connect(check_userprofile_details) post_save.connect(create_project_permission, sender=Project)
def email(self): return self.user.email @models.permalink def get_absolute_url(self): return ('player_profile', [self.user.username]) # Code to create new player classes after registration from registration.signals import user_activated def activate_player(sender, user, request, **kwarg): player = Player.objects.get(user=user) player.get_new_assignment() user_activated.connect(activate_player) class Character(models.Model): class Meta: verbose_name = u'Personage' verbose_name_plural = u'Personages' datecreated = models.DateTimeField(auto_now_add=True) datechanged = models.DateTimeField(auto_now=True) name = models.CharField(max_length=255, help_text='Naam van het personage') onelinebio = models.CharField(max_length=255, blank=True) biography = models.TextField(blank=True)
#from django.dispatch import receiver from registration.signals import user_activated from pipeline.models import MessageTemplate #@receiver(user_activated, sender=MyModel) #def my_handler(sender, **kwargs): def login_on_activation(sender, user, request, **kwargs): user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) def create_stuff_on_activation(sender, user, request, **kwargs): template = MessageTemplate() template.owner = user template.title = u'simple template' # regexp # template template.save() user_activated.connect(login_on_activation) user_activated.connect(create_stuff_on_activation)
def __unicode__(self): return u'Profile link.' @models.permalink def get_absolute_url(self): return self.url # Mozilla persona flow: # Welcome email when a new account is created: user_created.connect( communications.send_welcome_email, dispatch_uid='browserid_welcome_email') # Create a profile on new account creation: user_created.connect( Profile.active.get_or_create_for_user, dispatch_uid='browserid_create_profile') # US Ignite registration flow: # Welcome email when new account is created: user_activated.connect( communications.send_welcome_email, dispatch_uid='registration_welcome_email') user_activated.connect( Profile.active.get_or_create_for_user, dispatch_uid='registration_create_profile') # Search: watson.register( Profile.objects.filter(is_public=True, user__is_active=True), search.ProfileSearchAdapter )
def view_locale(request): loc_info = "getlocale: " + str(locale.getlocale()) + \ "<br/>getdefaultlocale(): " + str(locale.getdefaultlocale()) + \ "<br/>fs_encoding: " + str(sys.getfilesystemencoding()) + \ "<br/>sys default encoding: " + str(sys.getdefaultencoding()) return HttpResponse(loc_info) class HomeView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['stories'] = Story.objects.all().order_by('-date_created')[:5] context['image'] = Source.objects.filter(source_type__label='photograph').filter(personassociatedsource__association__label='primary topic of').order_by('?')[0] return context class ContributeView(TemplateView): template_name = 'contribute.html' def user_created(sender, user, request, **kwargs): g = Group.objects.get(name='contributor') g.user_set.add(user) g.save() user_activated.connect(user_created)
dd_orders = DocDataPaymentOrder.objects.filter(email=user.email).all() from bluebottle.wallposts.models import SystemWallPost wallposts = None for dd_order in dd_orders: dd_order.customer_id = user.id dd_order.save() dd_order.order.user = user dd_order.order.save() dd_order.order.donations.update(user=user) ctype = ContentType.objects.get_for_model(Donation) for donation_id in dd_order.order.donations.values_list('id', flat=True): qs = SystemWallPost.objects.filter(related_type=ctype, related_id=donation_id) if not wallposts: wallposts = qs else: pass # This causes errors... # wallposts += qs if wallposts: wallposts.update(author=user) # On account activation try to connect anonymous donations to this fails. user_activated.connect(link_anonymous_donations) from signals import * from fundmail import *
from registration.signals import user_activated from socialregistration.forms import UserForm from userprofile.models import UserProfile class SocialUserForm(UserForm): """ A UserForm that also creates a UserProfile on saving """ def save(self, *args, **kwargs): user = super(SocialUserForm, self).save(*args, **kwargs) UserProfile.objects.create(user=user) def create_userprofile(sender, **kwargs): userprofile = UserProfile.objects.create(user=kwargs.get('user')) user_activated.connect(create_userprofile, dispatch_uid="asdf")
from django.db import models from django.contrib.auth.models import User, Group from registration.supplements.base import RegistrationSupplementBase from registration.backends import get_backend from registration.signals import user_activated # Custom Registration Fields to gather more information about the user. class RegistrationCustomFields(RegistrationSupplementBase): institution = models.CharField("Institution Name", max_length=100) full_name = models.CharField("Full Name", max_length=100) def __unicode__(self): # a summary of this supplement return "%s (%s)" % (self.institution, self.full_name) # Automatically assign a user to research group when the account is activated # Done through user_activated signal def assign_user_to_group(sender, user, password, is_generated, request, **kwargs): backend = get_backend() g = Group.objects.get(name='research') g.user_set.add(user) user_activated.connect(assign_user_to_group)
def get_short_name(self): return self.username def __unicode__(self): return '%s - %s' % (self.email, self.username) def avatar_thumb(self): if self.image: return '<img src="%s%s" width="80px" height="80px"/>' %\ (settings.MEDIA_URL, get_thumbnail(self.image, '80x80', crop='center', quality=99).name) else: return '<img src="%simg/blank_user_80_80.jpg" width="80px" height="80px"/>' % settings.STATIC_URL avatar_thumb.short_description = 'Avatar' avatar_thumb.allow_tags = True def user_activated_handler(sender, user, request, **kwargs): # do something after account activation pass user_activated.connect(user_activated_handler, sender=None) def user_registered_handler(sender, user, request, **kwargs): # do something after account registration pass user_registered.connect(user_registered_handler, sender=None)
from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login from registration.signals import user_registered, user_activated def login_on_registration_or_activation(sender, user, request, **kwargs): user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) user_registered.connect(login_on_registration_or_activation) user_activated.connect(login_on_registration_or_activation) AuthenticationForm.base_fields['username'].max_length = 150 AuthenticationForm.base_fields['username'].widget.attrs['maxlength'] = 150 AuthenticationForm.base_fields['username'].validators[0].limit_value = 150 AuthenticationForm.base_fields['username'].label = "Email Address:"
derived_from = CharField(max_length=64, blank=True) creator = models.ForeignKey(User) status = IntegerField(null=True, default=1) author = CharField(max_length=100, blank=True, default="") editor = CharField(max_length=100, blank=True, default="") licensor = CharField(max_length=100, blank=True, default="") maintainer = CharField(max_length=100, blank=True, default="") translator = CharField(max_length=100, blank=True, default="") coeditor = CharField(max_length=100, blank=True, default="") def to_dict(self): material = dict() material['id'] = self.id material['material_id'] = self.material_id material['material_type'] = int(self.material_type) material['text'] = self.text material['version'] = self.version material['title'] = self.title material['description'] = self.description material['categories'] = self.categories material['status'] = self.status material['modified'] = self.modified if self.author: material['author'] = self.author return material user_activated.connect(user_activated_callback, dispatch_uid="ACTIVE_USER")
from registration.signals import user_registered, user_activated from registration.models import RegistrationProfile from researcher_UI.models import * from django.contrib.auth import login, authenticate from django.contrib.sites.models import Site def save_researcher_profile_receiver(sender, user, profile, request, **kwargs): researcher_profile, created = researcher.objects.get_or_create( user=profile.user) profile.user.first_name = profile.supplement.first_name profile.user.last_name = profile.supplement.last_name researcher_profile.institution = profile.supplement.institution researcher_profile.position = profile.supplement.position profile.user.save() researcher_profile.save() def activate_user_profile_receiver(sender, user, request, **kwargs): if not user.is_active: user.is_active = True user.backend = 'django.contrib.auth.backends.ModelBackend' user.save() login(request, user) user_registered.connect(save_researcher_profile_receiver) user_activated.connect(activate_user_profile_receiver)
from django.contrib import admin from models import User, UserProfile from django.contrib.auth.signals import user_logged_in from django.db.models import signals # 3rd-party ``registration`` app: connect up the signals import views from registration.signals import user_registered, user_activated class UserProfileAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'is_validated', 'affiliation', 'country', 'reputation', 'bio', 'uri', 'openid', 'contactable_via_site', 'allow_user_to_email') list_display_links = ('user', ) list_per_page = 1000 ordering = ('user', ) admin.site.register(UserProfile, UserProfileAdmin) # Hook up the signals here. Doing it in models.py results in circular imports. user_registered.connect(views.create_new_account) user_activated.connect(views.account_activation) user_logged_in.connect(views.user_logged_in) # Create a ``UserProfile`` for every user signals.post_save.connect(views.create_new_account, User)
""" my_ct = ContentType.objects.get_for_model(self) # get all user-specific permissions user_levels = {} for rm in UserObjectRoleMapping.objects.filter(object_id=self.id, object_ct=my_ct).all(): user_levels[rm.user.username] = rm.role.codename levels = {} for rm in GenericObjectRoleMapping.objects.filter(object_id=self.id, object_ct=my_ct).all(): levels[rm.subject] = rm.role.codename levels['users'] = user_levels return levels # Logic to login a user automatically when it has successfully # activated an account: from registration.signals import user_activated from django.contrib.auth import login def autologin(sender, **kwargs): user = kwargs['user'] request = kwargs['request'] # Manually setting the default user backed to avoid the # 'User' object has no attribute 'backend' error user.backend = 'django.contrib.auth.backends.ModelBackend' # This login function does not need password. login(request, user) user_activated.connect(autologin)
from registration.contrib.autologin.conf import settings def is_auto_login_enable(): """get whether the registration autologin is enable""" if not settings.REGISTRATION_AUTO_LOGIN: return False if 'test' in sys.argv and not getattr(settings, '_REGISTRATION_AUTO_LOGIN_IN_TESTS', False): # Registration Auto Login is not available in test to prevent the test # fails of ``registration.tests.*``. # For testing Registration Auto Login, you must set # ``_REGISTRATION_AUTO_LOGIN_IN_TESTS`` to ``True`` return False return True def auto_login_reciver(sender, user, password, is_generated, request, **kwargs): """automatically log activated user in when they have activated""" if not is_auto_login_enable() or is_generated: # auto login feature is currently disabled by setting or # the user was activated programatically by Django Admin action # thus no auto login is required. return # A bit of a hack to bypass `authenticate()` backend = get_backends()[0] user.backend = '%s.%s' % (backend.__module__, backend.__class__.__name__) login(request, user) user_activated.connect(auto_login_reciver)
return notification @property def type(self): return NOTIFICATION_TYPES.get(self.type_id, None) def is_read(self): # FIXME: this still modifies the model if self.read is None and (not hasattr(self.type, 'is_read') or hasattr(self.type, 'is_read') and self.type.is_read(self)): self.read = now() self.save() return self.read def html(self): try: template = get_template('heronotification/%s.html' % self.type.__name__.lower()) except TemplateDoesNotExist: template = get_template('heronotification/notification_base.html') rendered = mark_safe(template.render(Context({'notification': self}))) return rendered def welcome_new_user(sender, user, request, **kwargs): welcome(user, get_system_user()) user_activated.connect(welcome_new_user)
for rm in UserObjectRoleMapping.objects.filter(object_id=self.id, object_ct=my_ct).all(): user_levels[rm.user.username] = rm.role.codename levels = {} for rm in GenericObjectRoleMapping.objects.filter( object_id=self.id, object_ct=my_ct).all(): levels[rm.subject] = rm.role.codename levels['users'] = user_levels return levels # Logic to login a user automatically when it has successfully # activated an account: from registration.signals import user_activated from django.contrib.auth import login def autologin(sender, **kwargs): user = kwargs['user'] request = kwargs['request'] # Manually setting the default user backed to avoid the # 'User' object has no attribute 'backend' error user.backend = 'django.contrib.auth.backends.ModelBackend' # This login function does not need password. login(request, user) user_activated.connect(autologin)
from django.core,mail import send_mail from registration.signals import user_activated import urllib2 import json def fullContactCollect(email): api_key = '3558403aafc12f64' email = email fullURL = 'https://api.fullcontact.com/v2/person.json?apiKey='+api_key+ loadUrl = urllib2.urlopen(fullURL) jsonData = json.load(loadUrl) return jsonData def fullContactEmailSend(sender, user, request, **kwargs): email = user.email data = fullContactCollect(email) if data['status']==200: messgae= data send_mail("Full Contact Data", data, '*****@*****.**', '*****@*****.**', fail_silently=False) user_activated.connect(fullContactEmailSend)
from registration.backends.default.views import RegistrationView from .forms import SmasherRegistrationForm, ImageUploadForm from django.contrib.auth.models import User from .models import UserProfile import json import urllib, urllib2 def associate_profile(sender, user, request, **kwargs): email = user.email # If this function gets called, then the userprofile must exist up = UserProfile.objects.get(email__iexact=email) up.user = user up.save() user_activated.connect(associate_profile) class SmasherRegistrationView(RegistrationView): form_class = SmasherRegistrationForm success_url = '/?reg=true' class TestView(View): def get(self, request): if not request.user.is_superuser: return render(request, 'registration/login.html') # # url = 'http://api.genderize.io/?name=' users = list(User.objects.all()) for user in users:
from registration.signals import user_activated from medialibrary.models import MediaLibrary def registration_user_activated_signal(sender, **kwargs): """ receive signal from django-registration for when a new user has activated their account. Upon activation you will want to create a default UserProfile (model in django-profiles app). """ if 'user' in kwargs: user = kwargs['user'] if not MediaLibrary.objects.filter(user=user).count(): pml = MediaLibrary(user=user) pml.save() user_activated.connect(registration_user_activated_signal)
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from registration.signals import user_registered, user_activated from datawinners.accountmanagement.post_registration_events import ngo_user_created from datawinners.accountmanagement.post_activation_events import create_org_database user_registered.connect(ngo_user_created) user_activated.connect(create_org_database)
reporter = models.ForeignKey(User, related_name='reported report') content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') from registration.signals import user_activated from django.contrib.auth import login, authenticate def login_on_activation(sender, user, request, **kwargs): """Logs in the user after activation""" user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) # Registers the function with the django-registration user_activated signal user_activated.connect(login_on_activation) SYSTEM_USER_NAME = "YouAreHero" def get_system_user(): """Return an unique system-user. Creates one if not existing.""" user, created = User.objects.get_or_create(username=SYSTEM_USER_NAME) return user def get_dummy_user(): return UserProfile(user=User(username="******")) def experience_for_comment(sender, comment, request, **kwargs):
def is_auto_login_enable(): """get whether the registration autologin is enable""" if not settings.REGISTRATION_AUTO_LOGIN: return False if 'test' in sys.argv and not getattr( settings, '_REGISTRATION_AUTO_LOGIN_IN_TESTS', False): # Registration Auto Login is not available in test to prevent the test # fails of ``registration.tests.*``. # For testing Registration Auto Login, you must set # ``_REGISTRATION_AUTO_LOGIN_IN_TESTS`` to ``True`` return False return True def auto_login_reciver(sender, user, password, is_generated, request, **kwargs): """automatically log activated user in when they have activated""" if not is_auto_login_enable() or is_generated: # auto login feature is currently disabled by setting or # the user was activated programatically by Django Admin action # thus no auto login is required. return # A bit of a hack to bypass `authenticate()` backend = get_backends()[0] user.backend = '%s.%s' % (backend.__module__, backend.__class__.__name__) login(request, user) user_activated.connect(auto_login_reciver)
user.firstname = participant.name participant.email_id = user.email participant.phone_no = form.data["phone_no"] if int(form.data["college"]) == -1: if form.data["add_your_college"] is not None: new_college = College(name=form.data["add_your_college"]) new_college.save() participant.college = new_college else: raise Exception("No College name specified") else: participant.college = College.objects.get(pk=form.data["college"]) participant.roll_no = form.data["rollno"] participant.save() for e in form.data.getlist("events"): participant.events.add(e) def user_verification_updated(sender, user, request, **kwargs): participant = Participant.objects.filter(user__user=user) if participant is not None and len(participant) == 1: participant = participant[0] participant.email_verified = "Yes" participant.save() from registration.signals import user_registered, user_activated user_registered.connect(user_created) user_activated.connect(user_verification_updated)
page = models.ForeignKey(Page) def __unicode__(self): return self.key # Register signals, this is done in models.py to make sure they're registered early in the app life cycle def new_user_activated(sender, user, request, **kwarg): g = Group.objects.get(name='Member') g.user_set.add(user) def new_social_users_handler(sender, user, response, details, **kwargs): g = Group.objects.get(name='Member') g.user_set.add(user) user_activated.connect(new_user_activated) socialauth_registered.connect(new_social_users_handler, sender=None) # Create CMS Plugins class ItemListPlugin(CMSPlugin): trip = models.ForeignKey(Trip) class IterableLazyObject(SimpleLazyObject): def __iter__(self): if self._wrapped is None: self._setup() return self._wrapped.__iter__()