Exemplo n.º 1
0
    def __unicode__(self):
        return self.user
	def user_registered_callback(sender, user, request, **kwargs):
		profile = ExUserProfile(user = user)
		profile.is_human = bool(request.POST["is_human"])
		profile.save()

	user_registered.connect(user_registered_callback)
 def test_signal_sent(self):
     signal_user = set()
     def user_registered_signal_handler(sender, request, user, **kwargs):
         signal_user.add(user)
     user_registered.connect(
         user_registered_signal_handler)
     u = self.b.register(self.req, email='*****@*****.**')
     self.assertIn(u, signal_user)
Exemplo n.º 3
0
def show_profile(request):

    user_registered.connect(user_registered_callback)

    user = request.user
    form = EditProfileForm(initial={'first_name': user.first_name,
                                    'last_name': user.last_name,
                                    'email': user.email})
    context = {
        "form": form
    }
    return render(request, 'accounts/profile.html', context)
Exemplo n.º 4
0
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
Exemplo n.º 5
0
class UserProfile(FacebookProfileModel):
    # user = models.OneToOneField(User)
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(default='', blank=False, max_length=20)
    last_name = models.CharField(default='', blank=False, max_length=20)
    address = models.CharField(default='', blank=True, max_length=60)
    city = models.CharField(default='', blank=True, max_length=20)
    zipcode = models.IntegerField(default=85111, blank=False, max_length=5)
    phone = models.CharField(default='', blank=True, max_length=12)
    email = models.EmailField(default='', blank=True, max_length=40)
    has_dog = models.BooleanField(default=False)
    locked_gate = models.BooleanField(default=False)
    pest_customer = models.BooleanField(default=False)
    weed_customer = models.BooleanField(default=False)
    current_balance = models.DecimalField(default=0.00,
                                          blank=True,
                                          max_digits=6,
                                          decimal_places=2)
    balance_due_date = models.DateField(blank=True, null=True)
    next_appointment = models.DateField(blank=True, null=True)
    public = models.BooleanField(default=False, blank=True)
    notes = models.TextField(default='', blank=True, max_length=400)

    # user_profile_placeholder = PlaceholderField('user_profile_placeholder')

    class Meta:
        verbose_name = _('user profile')
        verbose_name_plural = _('user profiles')

    def __unicode__(self):
        return (self.user.username)

    def attrs(self):
        out = []
        for field in self._meta.fields:
            out.extend([field.name, getattr(self, field.name)])
        return (out)

    def user_registered_callback(sender, user, request, **kwargs):
        profile = UserProfile(user=user)
        profile.first_name = request.POST["first_name"]
        profile.last_name = request.POST["last_name"]
        profile.email = request.POST["email"]
        profile.zipcode = int(request.POST["zipcode"])
        profile.save()
        user.first_name = request.POST["first_name"]
        user.last_name = request.POST["last_name"]
        user.email = request.POST["email"]
        user.save()

    user_registered.connect(user_registered_callback)
Exemplo n.º 6
0
class UserProfile(models.Model):
	user = models.ForeignKey(User, unique=True)
	full_name = models.CharField(max_length=120,blank=True, null=True)

	def __unicode__(self): #python 3 __str__
		return self.user #dispayed in signup field in admin page

	def user_registered_callback(sender, user, request, **kwargs):
	    profile = UserProfile(user=user)
	    profile.full_name = request.POST["full_name"]
	    profile.save()
 	
 	user_registered.connect(user_registered_callback)


# class Contact(models.Model):
# 	email = models.EmailField()
# 	full_name = models.CharField(max_length=120,blank=True, null=True)
# 	message = models.TextField()
# 	timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

# 	def __unicode__(self): #python 3 __str__
# 		return self.email #dispayed in signup field in admin page
Exemplo n.º 7
0
            return potential
        suffix = str(uuid.uuid4()).split('-')[0]


def activate_user(user, request, **kwargs):
    user.is_active = True
    user.save()

    user = authenticate(username=request.POST['username'],
                        password=request.POST['password1'])
    login(request, user)


def get_lexers_list():
    lexers = list(get_all_lexers())

    for l in lexers:
        if l[0] == 'ANTLR With Java Target':
            lexers.remove(l)

    lexers.append((
        'Markdown',
        ('markdown', ),
    ))
    lexers = sorted(lexers)

    return lexers


user_registered.connect(activate_user)
Exemplo n.º 8
0
class TeacherProfile(UserProfile):
  teacher_code = models.CharField(max_length=32)


class TeacherProfileAttributes(models.Model):
	teacher					= models.OneToOneField(TeacherProfile)
	bio							= models.CharField(null=True, verbose_name="Bio", max_length=1024)
	linkedIn_url 		= models.CharField(null=True, verbose_name="LinkedIn",max_length=32)
	twitter_handle 	= models.CharField(null=True, verbose_name="Twitter", max_length=32)
	college 				= models.CharField(null=True, verbose_name="College", max_length=128)
	gradschool			= models.CharField(null=True, verbose_name="Grad School", max_length=128)
	major   				= models.CharField(null=True, verbose_name="Major", max_length=128)
	skills					= models.CharField(null=True, verbose_name="Skills", max_length=128)
	expertise				= models.CharField(null=True, verbose_name="Expertise", max_length=128)


class TeacherRating(Rating):
	teacher = models.ForeignKey('TeacherProfile')

class StudentProfile(UserProfile):
	dummy = models.CharField(max_length=32)
	
	
class StudentProfileAttributes(models.Model):
	student					= models.OneToOneField(StudentProfile)
	bio							= models.CharField(null=True, verbose_name="Bio", max_length=1024)


from registration.signals import user_registered
user_registered.connect(extra_methods.registerUserProfile)
Exemplo n.º 9
0
                             null=True,
                             blank=True)
    date_of_birth = models.DateField(_('YYYY-MM-DD'), null=True, blank=True)
    website = models.URLField(_('website'), null=True, blank=True)
    feedback = models.BooleanField(_('give feedback'), default=False)
    comment = models.BooleanField(_('show comments'), default=True)
    role = models.CharField(max_length=2,
                            choices=ROLE_CHOICES,
                            blank=True,
                            null=True,
                            default='st')

    def __unicode__(self):
        return _("%s") % self.user.username

    def is_authenticated(self):
        return self.user.is_authenticated()

    class Meta:
        app_label = "userprofile"
        verbose_name = "user profile"
        verbose_name_plural = "user profiles"


def user_profile_callback(sender, user, request, **kwargs):
    profile = UserProfile(user=user)
    profile.save()


user_registered.connect(user_profile_callback)
Exemplo n.º 10
0
from django.contrib.auth.models import Group

from registration.signals import user_registered

from editor.models import UserRegionalInfo


def create_userregionalinfo(sender, user, request, **kwarg):
    group, created = Group.objects.get_or_create(name='Reporters')
    user.groups.add(group)
    UserRegionalInfo.objects.create(
        user=user,
        phone=request.POST.get('phone', ''),
        information=request.POST.get('information', ''),
    )
user_registered.connect(create_userregionalinfo)

Exemplo n.º 11
0
from django.db import models

from django.contrib.auth.models import Group, User
from registration.signals import user_registered

def get_upload_path(instance, filename):
        import os
        ext = os.path.splitext(filename)[1]
        ext = ext.lower()
        file_path = '{username}/profile_image/{name}.{ext}'.format(
            username=instance.user.username,name=filename, ext=ext) 
        return file_path
        
def user_registered_callback(sender, user, request, **kwargs):
    g = Group.objects.get(name='tripper') 
    g.user_set.add(user)
 
user_registered.connect(user_registered_callback)

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name="profile")
    picture = models.ImageField(upload_to=get_upload_path, blank=True)
    # Override the __unicode__() method to return out something meaningful!
    #def __str__(self):
        #return self.picture
        
Exemplo n.º 12
0
from django.contrib.auth.models import User
from django.db import models
from registration.signals import user_registered

class UserProfile(models.Model):
    SEX_CHOICES = (('F', 'Female'), ('M', 'Male'))
    user = models.OneToOneField(User)
    sex = models.CharField(max_length=1, choices=SEX_CHOICES, blank=True, null=True)
    dob = models.DateField('Date of Birth', blank=True, null=True)
    picture = models.ImageField('Profile Picture', upload_to='profile_picture', blank=True)

    def is_worker(self):
        return hasattr(self, 'workerprofile')

class WorkerProfile(UserProfile):
    deposit = models.DecimalField(decimal_places=2, max_digits=9, default=0)

def create_user_profile(sender, user, request, **kwargs):
    # If they are applying to be a worker, create the correct profile
    worker = request.POST.get('worker')
    if worker:
        WorkerProfile.objects.create(user=user)
    else:
        UserProfile.objects.create(user=user)

user_registered.connect(create_user_profile)
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
    subject = "".join(subject.splitlines())
    message = render_to_string(
        settings.REGISTRATION_NOTIFICATION_EMAIL_TEMPLATE_NAME, context)

    recipients = []
    if settings.REGISTRATION_NOTIFICATION_ADMINS:
        for userinfo in settings.ADMINS:
            recipients.append(userinfo[1])
    if settings.REGISTRATION_NOTIFICATION_MANAGERS:
        for userinfo in settings.MANAGERS:
            recipients.append(userinfo[1])
    if settings.REGISTRATION_NOTIFICATION_RECIPIENTS:
        method_or_iterable = settings.REGISTRATION_NOTIFICATION_RECIPIENTS
        if callable(method_or_iterable):
            recipients.extend(method_or_iterable())
        elif isinstance(method_or_iterable, (list, tuple)):
            recipients.extend(method_or_iterable)
        else:
            raise ImproperlyConfigured(
                ('``REGISTRATION_NOTIFICATION_RECIPIENTS`` must '
                 'be a list of recipients or function which return '
                 'a list of recipients (Currently the value was "%s")') %
                method_or_iterable)
    # remove duplications
    recipients = frozenset(recipients)

    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipients)


user_registered.connect(send_notification_email_reciver)
Exemplo n.º 15
0
 def ready(self):
     user_registered.connect(record_survey)
Exemplo n.º 16
0
        _('is public'), help_text=_('Profile is visible for others.'))

    avatar = StdImageField(_('avatar'),
                           upload_to=avatar_upload,
                           blank=True,
                           size=(settings.AVATAR_SIZE, settings.AVATAR_SIZE,
                                 True),
                           thumbnail_size=(settings.AVATAR_THUMBNAIL_SIZE,
                                           settings.AVATAR_THUMBNAIL_SIZE,
                                           True))

    def __unicode__(self):
        return 'Profile for %s' % self.user.username

    @property
    def age(self):
        d = datetime.date.today()
        if self.birth_date:
            return (d.year - self.birth_date.year) \
                    - int((d.month, d.day) \
                    < (self.birth_date.month, self.birth_date.day))
        else:
            return None

    @models.permalink
    def get_absolute_url(self):
        return ('profile-detail', (), {'username': self.user.username})


user_registered.connect(UserProfile.objects.profile_callback)
Exemplo n.º 17
0
class UserProfile(FacebookProfileModel):
    # user = models.OneToOneField(User)
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(default='', blank=False, max_length=20)
    last_name = models.CharField(default='', blank=False, max_length=20)
    address = models.CharField(default='', blank=True, max_length=60)
    city = models.CharField(default='', blank=True, max_length=20)
    zipcode = models.IntegerField(default=85111, blank=False, max_length=5)
    phone = models.CharField(default='', blank=True, max_length=12)
    email = models.EmailField(default='', blank=True, max_length=40)
    # next_appointment = models.DateTimeField(auto_now_add=True,blank=True)
    # balance = models.DecimalField(default=0.0,blank=True,max_digits=6,decimal_places=2)
    # dog = models.BooleanField(default=False,blank=True)
    web_url = models.URLField(blank=True, null=True)
    NONE = 'None'
    BASIC = 'Basic'
    PREMIUM = 'Premium'
    support_plan_choices = ((NONE, 'None'), (BASIC, 'Basic'), (PREMIUM,
                                                               'Premium'))
    support_plan = models.CharField(default=NONE,
                                    choices=support_plan_choices,
                                    max_length=7)
    current_balance = models.DecimalField(default=0.00,
                                          blank=True,
                                          max_digits=6,
                                          decimal_places=2)
    balance_due_date = models.DateField(blank=True, null=True)
    public = models.BooleanField(default=False, blank=True)
    notes = models.TextField(default='', blank=True, max_length=200)

    # user_profile_placeholder = PlaceholderField('user_profile_placeholder')

    class Meta:
        verbose_name = _('user profile')
        verbose_name_plural = _('user profiles')

    def __unicode__(self):
        return (self.user.username)

    def attrs(self):
        out = []
        for field in self._meta.fields:
            out.extend([field.name, getattr(self, field.name)])
        return (out)

    def user_registered_callback(sender, user, request, **kwargs):
        profile = UserProfile(user=user)
        profile.first_name = request.POST["first_name"]
        profile.last_name = request.POST["last_name"]
        profile.email = request.POST["email"]
        if request.POST["business_zipcode"] == '':
            pass
        else:
            profile.zipcode = int(request.POST["business_zipcode"])
        profile.save()
        user.first_name = request.POST["first_name"]
        user.last_name = request.POST["last_name"]
        user.email = request.POST["email"]
        user.save()

    user_registered.connect(user_registered_callback)
Exemplo n.º 18
0
    user_profile.opportunities_to_teach = form.data['opportunities_to_teach']
    user_profile.possible_to_teach = form.data['possible_to_teach']
    user_profile.ethnicity = form.data['ethnicity']
    user_profile.race = form.data['race']
    user_profile.age = form.data['age']
    user_profile.highest_degree = form.data['highest_degree']
    user_profile.consented = form.data['consented']

    user_profile.state = u','.join(request.POST.getlist('state'))
    user_profile.work_description = \
        u','.join(request.POST.getlist('work_description'))

    user_profile.save()


user_registered.connect(update_user_profile)


class LoggedInMixinSuperuser(object):
    @method_decorator(user_passes_test(lambda u: u.is_superuser))
    def dispatch(self, *args, **kwargs):
        return super(LoggedInMixinSuperuser, self).dispatch(*args, **kwargs)


class ReportView(LoggedInMixinSuperuser, View):

    def get(self, request):
        report = TeachDentistryReport()

        # setup zip file for the key & value file
        response = HttpResponse(content_type='application/zip')
Exemplo n.º 19
0
    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):
    user_with_backend = authenticate(username=user.username,
                                     password=request.POST['password1'])
    login(request, user_with_backend)


user_registered.connect(log_in_user)
Exemplo n.º 20
0
from django.contrib.auth.models import Permission


def user_registered_handler(sender, **kwargs):
    """signal intercept for user_registered"""
    request = kwargs['request']
    new_user = authenticate(username=request.POST['username'], password=request.POST['password1'])
    view_permissions = ['view_project', 'view_issuetype', 'view_priority', 'view_status', 'view_milestone',
                        'view_issue', 'view_comment', 'view_commit', ]
    add_permissions = ['add_project', 'add_issuetype', 'add_priority', 'add_status', 'add_milestone', 'add_issue',
                       'add_comment', 'add_commit', ]
    change_permissions = ['change_project', 'change_issuetype', 'change_priority', 'change_status', 'change_milestone',
                          'change_issue', 'change_comment', 'change_commit', ]
    delete_permissions = ['delete_project', 'delete_issuetype', 'delete_priority', 'delete_status', 'delete_milestone',
                          'delete_issue', 'delete_comment', 'delete_commit', ]
    for v_perm in list(set().union(view_permissions, add_permissions, change_permissions, delete_permissions)):
        permission = Permission.objects.get(codename=v_perm)
        if permission:
            new_user.user_permissions.add(permission)


user_registered.connect(user_registered_handler)
admin.site.register(Project)
admin.site.register(IssueType)
admin.site.register(Priority)
admin.site.register(Status)
admin.site.register(Milestone)
admin.site.register(Issue)
admin.site.register(Comment)
admin.site.register(Commit)
Exemplo n.º 21
0
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


AUTO_USERNAME_PREFIX = ":auto:"
USERNAME_MAX_LENGTH = User._meta.get_field("username").max_length
DIGEST_LENGTH = USERNAME_MAX_LENGTH - len(AUTO_USERNAME_PREFIX)


def browserid_create_user(email):
    """Create and return a new User for a new BrowserID login."""
    digest = base64.urlsafe_b64encode(hashlib.sha1(email).digest())
    username = AUTO_USERNAME_PREFIX + digest[:DIGEST_LENGTH]

    user = User.objects.create_user(username=username, email=email)
    add_new_user_role(user)

    return user


def add_new_user_role(user, **kwargs):
    role = preferences.CorePreferences.default_new_user_role
    if role is not None:
        # Have to use groups, not roles, because registration doesn't send our
        # proxy User with its signal.
        user.groups.add(role)


user_registered.connect(add_new_user_role)
Exemplo n.º 22
0
 
def user_registered_callback(sender, user, request, **kwargs):
    profile = UserProfile( user = user )
    try:
    	profile.gpstc_sailor_id = request.POST["gpstc_sailor_id"]
    	profile.gpstc_team_id = request.POST["gpstc_team_id"]
	profile.FullName=request.POST["FullName"]
	profile.NickName=request.POST["NickName"]
    except:
        profile.gpstc_sailor_id = 0
	profile.gpstc_team_id=0
	profile.FullName=''
	profile.NickName=''
    profile.save()

user_registered.connect(user_registered_callback, dispatch_uid="gps_user_registered_callback")




##
## Models for GPS app 
##

#class QuerySetManager(models.Manager):
#	def get_query_set(self):
#		return self.model.QuerySet(self.model)
#	def __getattr__(self, attr, *args):
#		return getattr(self.get_query_set(), attr, *args)

Exemplo n.º 23
0
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)
Exemplo n.º 24
0
from django.db import models
from django.contrib.auth.models import User
from registration.signals import user_registered
from timezones.fields import TimeZoneField
from timezones.utils import localtime_for_timezone, adjust_datetime_to_timezone

# Create your models here.


class UserProfile(models.Model):
    user = models.ForeignKey(User, related_name="profiles")
    timezone = TimeZoneField()

    def __unicode__(self):
        return self.user.username

    @classmethod
    def create_from_registration(cls, sender, user, request, **kwargs):
        # Will get here when registration.views.register sends the
        # user_registered signal. Form class set to CustomRegistrationForm
        # for view so assumed timezone will be included with request.
        print request.POST
        print request.POST["timezone"]
        UserProfile.objects.create(user=user, timezone=request.POST["timezone"])


user_registered.connect(UserProfile.create_from_registration)
Exemplo n.º 25
0
    )

    member = models.BooleanField(default=False)
    membershipType = models.IntegerField(choices=MEMBERSHIP_TYPES,
                                         default=NONE_MTYPE)
    membershipExpiry = models.DateTimeField(null=True, blank=True)

    # specific per game
    customWordwallsStyle = models.CharField(max_length=1000, blank=True)
    wordwallsSaveListSize = models.IntegerField(default=0)
    wordwallsMedals = models.TextField(null=True, blank=True)

    # project-wide
    defaultLexicon = models.ForeignKey(Lexicon, default=getLexicon)
    avatarUrl = models.CharField(null=True, blank=True, max_length=512)
    additional_data = models.TextField(default='{}', blank=True)

    def __unicode__(self):
        return "Profile for " + self.user.username


def user_registered_handler(sender, user, request, **kwargs):
    profile = AerolithProfile()
    profile.user = user
    profile.save()


user_registered.connect(user_registered_handler)

# specific tables
Exemplo n.º 26
0
class Day(models.Model):
    goal = models.ForeignKey(Goal)
    date = models.DateTimeField('date done')

    def __str__(self):
        return str(self.date)

    class Meta:
        ordering = ['date']


class Credit(models.Model):
    user = models.ForeignKey(User)
    credit = models.IntegerField(default=1)

    def __unicode__(self):
        return '%s %d' % (self.user.username, self.credit)

class Achievement(models.Model):
    user = models.ForeignKey(User)
    reason = models.TextField()

    def __unicode__(self):
        return '%s' % (self.reason)


def add_credit(sender, user, request, **kwargs):
    Credit.objects.create(user=user, credit=1)

user_registered.connect(add_credit)
Exemplo n.º 27
0
 
# def logout_page(request):
#     logout(request)
#     return HttpResponseRedirect('/')



# Create user profile after receiving activation signal
from registration.signals import user_registered
 
def user_registered_profile(sender, user, request, **kwargs):
	profile = Profile(user_id=user.id)
	profile.email = user.email
	profile.save()
 
user_registered.connect(user_registered_profile)






def home(request):
	
	gigs = Gig.objects.filter(status=True).order_by('create_time')
	return render(request, 'home.html', {"gigs": gigs})

	# gig_list = Gig.objects.filter(status=True)
	# page = request.GET.get('page', 1)
	# paginator = Paginator(gig_list, 20)
	# try:
Exemplo n.º 28
0
    out = beta_test_items()

    message_body = "ID: %s" % (out['name'])
    message_body += "\nHaves:\n"
    for have in out["haves"]:
        message_body += "%s" % (have)

    message_body += "\nNeeds:\n"
    for have in out["needs"]:
        message_body += "%s" % (have)

    instructions = "%s\n%s\n%s" % (message_front, message_body, message_end)

    message = NotificationMessage(sender=user,
                                  notify_type=NotificationMessage.BETA_TEST,
                                  contents=instructions)
    message.send()

post_save.connect(create_profile, sender=User, dispatch_uid="users-profilecreation-signal")
post_save.connect(create_api_key, sender=User)
user_registered.connect(activate_user)
user_registered.connect(send_verification_email)

class EmailSender:
    MESSAGES = '*****@*****.**'
    INVENTORY = '*****@*****.**'
    REQUESTS = '*****@*****.**'
    ADMIN = '*****@*****.**'
    FEEDBACK = '*****@*****.**'
Exemplo n.º 29
0
from django.dispatch import receiver

from registration.signals import user_registered

from cross_founding_platform.cross_founding.forms import BackerRegistrationForm
from cross_founding_platform.cross_founding.models import Backer

@receiver(user_registered)
def backer_registration(sender, user, request, **kwargs):
    form = BackerRegistrationForm(request.POST)

    user.first_name = form.data["first_name"]
    user.last_name = form.data["last_name"]
    user.save()

    backer = Backer(user=user)
    backer.gender = form.data["gender"]
    backer.location = request.META['REMOTE_ADDR']
    backer.dob_at = form.get_dob()
    backer.twitter_user = form.data['twitter_user']
    backer.facebook_user = form.data['facebook_user']
    backer.access_token = form.data['access_token']if form.data['access_token'] != '' else None
    backer.secret_token = form.data['secret_token']if form.data['secret_token'] != '' else None
    backer.expire_token = form.data['expire_token']if form.data['expire_token'] != '' else None
    backer.third_party_id = form.data['third_party_id']if form.data['third_party_id'] != '' else None
    backer.save()

user_registered.connect(backer_registration)
Exemplo n.º 30
0
from django.db.models import permalink

from registration.signals import user_registered

from oncallr.notification.models import NOTIFICATION_CHOICES

PHONE_STATUSES = ( (0, "Unverified"), (1, "Verified") )

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.PROTECT)
    contact_method = models.PositiveSmallIntegerField(choices=NOTIFICATION_CHOICES, default=0)
    language_pref = models.CharField(verbose_name='Language Preference', max_length=4, choices=settings.LANGUAGES)
    # only contains teams that a user is a memeber of, not a leader.
    teams = models.ManyToManyField(Team, related_name='teams', blank=True, null=True)

    def __unicode__(self):
        return self.user.username

    @permalink
    def get_absolute_url(self):
        return ('profile_detail', None, {'username': self.user.username})

def post_registration_profile_creation(sender, **kwargs):
    """ Create a profile for a user post registration. """
    user = kwargs.pop('user')
    request = kwargs.pop('request')

    Profile.objects.create(user=user)

user_registered.connect(post_registration_profile_creation)
Exemplo n.º 31
0
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:"
Exemplo n.º 32
0
    '''
    try:
        request = kwargs.get('request')
        first_name = ''
        last_name = ''
        if request is not None:            
            first_name = request.POST.get('first_name','')
            last_name = request.POST.get('last_name','')
            city = request.POST.get('city','')
            zip = request.POST.get('zip','')
            bike = request.POST.get('bike','')
            email = request.POST['email']
            avatar_hash = hashlib.md5(email.lower()).hexdigest()
                        
            user = kwargs.get('user')
            if user is not None:
                logger.debug('User is good')
                user.first_name = first_name
                user.last_name = last_name
                user.save()
                profile, created = UserProfile.objects.get_or_create(user=user)
                profile.city = city
                profile.zip = zip
                profile.bike = bike
                profile.avatar = avatar_hash
                profile.save()
    except:
        logger.error('Failed to save user profile data: %s' % request.POST)

user_registered.connect(save_user_names) 
Exemplo n.º 33
0
                         key=lambda x: x[0])

        article_list = [j[i] for k, g in groups for i, j in enumerate(g)]

        return article_list, [(tag, topics[tag], value) for tag, value in enumerate(article_tags)]


def user_registered_callback(sender, user, request, **kwargs):
    """
    :param user: user_auth model object
    Callback to create profile when creating a user auth object
    """
    profile = UserProfileRec(user=user)

    """
    initialise profile ratings
    """
    profile_topics = {"twitter_topics": {topics.index(t): 0 for t in topics},
                      "explicit_topics": {topics.index(t): 0 for t in topics},
                      "clicked_topics": Counter({topics.index(t): 0 for t in topics}),
                      "shown_topics": Counter({topics.index(t): 0 for t in topics})}

    profile.profile_topics = base64.b64encode(pickle.dumps(profile_topics))

    profile.save()

"""
connect callback to registration event
"""
user_registered.connect(user_registered_callback)
Exemplo n.º 34
0
        notification = Notification()
        notification.user = instance
        notification.save()
        address = Address()
        address.save(user=instance)
        profile = UserProfile()
        profile.user = instance
        profile.address = address
        profile.save()

        today = datetime.date.today()
        default_state = SUBSCRIPTION_STATE_TRIAL
        if settings.FREE_SUBSCRIPTION:
            default_state = SUBSCRIPTION_STATE_FREE
        subscription = Subscription.objects.create(
            owner=instance,
            state=default_state,
            expiration_date=today +
            datetime.timedelta(settings.TRIAL_DURATION),
            transaction_id='TRIAL-%i%i%i-%i' %
            (today.year, today.month, today.day, instance.id))


def log_registration(sender, user, request, **kwargs):
    logger = logging.getLogger('aemanager')
    logger.info('%s <%s> has registered' % (user.username, user.email))


post_save.connect(user_post_save, sender=User)
user_registered.connect(log_registration)
Exemplo n.º 35
0
from teachercomapp.forms import UserRegistrationForm
from django.contrib.auth.models import User

from teachercomapp.models import Teacher

from registration.signals import user_registered


# create teacher takes as kwargs a form input from the registration form, including user info and the twilio info
def create_teacher(sender, **kwargs):
    request = kwargs['request'].POST
    form = UserRegistrationForm(request)
    extended_user = Teacher()
    extended_user.user = User.objects.get(username=request['username'])
    extended_user.twilio_account_sid = request['twilio_account_sid']
    extended_user.twilio_auth_token = request['twilio_auth_token']
    extended_user.twilio_number = request['twilio_number']
    extended_user.save()
    print "teacher created"


user_registered.connect(create_teacher)
Exemplo n.º 36
0
      

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    user_sets = models.ManyToManyField(Sets, blank = True)
    
    
    def __unicode__(self):
        return unicode(self.user)


from registration.signals import user_registered
def createUserProfile(sender, user, request, **kwargs):
    UserProfile.objects.get_or_create(user=user)

user_registered.connect(createUserProfile)

class KnownKanji(models.Model):
    #should be a foreign key
    kanji = models.ManyToManyField(Kanji)
    date_added = models.DateTimeField(auto_now_add = True)
    selected_kanji = models.BooleanField(default = False)
    user_profile = models.ManyToManyField(UserProfile)
    
    #im not sure what this is for....
    number_of_chosen_words = models.IntegerField(null = True)
    
    def __unicode__(self):
        return unicode(self.kanji)
        
    def display_kanji(self):
Exemplo n.º 37
0
        invites = self.filter(created_for_email__iexact=user.email)
        for i in invites:
            # Connect the user to the invites
            i.created_for_user = user
            # Handle the responses
            if i.response == 2:
                i.project.members.add(user)
            i.save()

class Invite(models.Model):
    """ A base model for invites """
    sha = models.CharField(_('sha'), max_length=40)
    date = models.DateField(_('date'), auto_now_add=True)
    response = models.PositiveIntegerField(choices=RESPONSE_CHOICES, default=1)
    project = models.ForeignKey(Project, related_name='')

    created_by = models.ForeignKey(User, related_name='send_invites')
    created_for_user = models.ForeignKey(User, related_name='created_invites', blank=True, null=True)
    created_for_email = models.EmailField(blank=True, null=True)

    objects = InviteManager()

    def __unicode__(self):
        created_for = self.created_for_user.username if self.created_for_user else self.created_for_email
        return '%(created_by)s invited %(created_for)s for %(project)s' % {'created_by': self.created_by.username,
                                                                           'created_for': created_for,
                                                                           'project': self.project.name}

user_registered.connect(Invite.objects.register_signal)
oid_associate.connect(Invite.objects.register_signal)
Exemplo n.º 38
0
from teachercomapp.forms import UserRegistrationForm
from django.contrib.auth.models import User

from teachercomapp.models import Teacher

from registration.signals import user_registered

# create teacher takes as kwargs a form input from the registration form, including user info and the twilio info
def create_teacher(sender, **kwargs):
    request = kwargs['request'].POST  
    form=UserRegistrationForm(request)
    extended_user = Teacher()
    extended_user.user = User.objects.get(username=request['username'])
    extended_user.twilio_account_sid = request['twilio_account_sid']
    extended_user.twilio_auth_token = request['twilio_auth_token']
    extended_user.twilio_number=request['twilio_number']
    extended_user.save()
    print "teacher created"

user_registered.connect(create_teacher)
Exemplo n.º 39
0
Arquivo: models.py Projeto: 9gix/golib
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from registration.signals import user_registered

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    contact = models.CharField(max_length=15, blank=True)
    address = models.TextField(max_length=250, blank=True)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

def update_user_profile(sender, user, request, **kwargs):
    data = request.POST
    user.first_name = data.get('first_name')
    user.last_name = data.get('last_name')
    user.save()
    user_profile, created = UserProfile.objects.get_or_create(user=user)
    user_profile.address = data.get('address')
    user_profile.contact = data.get('contact')
    user_profile.postal = data.get('postal')
    user_profile.save()

user_registered.connect(update_user_profile)
Exemplo n.º 40
0
        abstract = True


class Hacker(UserProfile):
    # position in company
    position = models.CharField(blank=False, null=False, max_length=200)

    def __unicode__(self):
        return self.get_name

    @classmethod
    def create_hacker(cls, sender, **kwargs):
        request, instance = kwargs['request'], kwargs['user']
        try:
            position = request.POST['position']
            cls(user=instance, position=position).save()
        except KeyError:
            #UserProfile(user = instance).save() #Default create just a profile
            pass

    @property
    def get_email(self):
        return self.user.email

    @property
    def get_name(self):
        return self.user.first_name + ' ' + self.user.last_name


user_registered.connect(Hacker.create_hacker)
Exemplo n.º 41
0
from django.contrib.auth import login

from registration.signals import user_registered
from notification import models as notification
from actstream.actions import follow

from dnstorm.app.models import Invitation

def login_on_registration(sender, user, request, **kwargs):
    """
    Logs in the user after registration.
    """
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)

user_registered.connect(login_on_registration)

def create_notice_types(app, created_models, verbosity, **kwargs):
    """
    Register notification types for django-notification.
    """
    notification.create_notice_type(
        'invitation',
        _('Invitation received'),
        _('you have received an invitation to collaborate in a problem'))
    notification.create_notice_type(
        'problem',
        _('Problem updated'),
        _('a problem you\'re contributing was updated'))

signals.post_syncdb.connect(create_notice_types, sender=notification)
Exemplo n.º 42
0
            if value:
                potential = "-".join([base, str(suffix)])
            else:
                potential = str(suffix)
        if not model.objects.filter(**{slugfield: potential}).count():
            return potential
        suffix = str(uuid.uuid4()).split("-")[0]


def activate_user(user, request, **kwargs):
    user = authenticate(
        username=request.POST["username"], password=request.POST["password1"]
    )
    login(request, user)


def get_lexers_list():
    lexers = list(get_all_lexers())

    for l in lexers:
        if l[0] == "ANTLR With Java Target":
            lexers.remove(l)

    lexers.append(("Markdown", ("markdown",)))
    lexers = sorted(lexers)

    return lexers


user_registered.connect(activate_user)
Exemplo n.º 43
0
        return data


class LogoutView(View):
    def get(self, request):
        django.contrib.auth.logout(request)
        messages.add_message(
            request, messages.SUCCESS, u"Atslēgšanās veiksmīga")
        return redirect('index')


class LoginView(View):
    def post(self, request):
        form = LoginForm(request.POST)
        if form.is_valid():
            user = django.contrib.auth.authenticate(**form.cleaned_data)
            if user:
                django.contrib.auth.login(request, user)
                return redirect('list_parcels')
        messages.add_message(
            request, messages.ERROR, u"E-pasts vai parole nepareiza")
        return redirect("registration_register")


def post_register(sender, **kwargs):
    messages.add_message(
        kwargs['request'], messages.SUCCESS, u"Reģistrācija veiksmīga")

user_registered.connect(post_register)

Exemplo n.º 44
0
from registration.signals import user_registered

from main.models import Profile

def create_profile(user, **kwargs):
    Profile.objects.create(user=user)

user_registered.connect(create_profile, dispatch_uid='main.signals.create_profile')
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):
    user_with_backend = authenticate(username=user.username,
                                     password=request.POST['password1'])
    login(request, user_with_backend)
user_registered.connect(log_in_user)
Exemplo n.º 46
0
        public_group = ExtendedGroup.objects.public_group()
        # need to check if Public group exists to avoid errors when creating
        # user accounts (like superuser and AnonymousUser) before the group
        # is created by init_refinery command
        if public_group:
            instance.groups.add(public_group)


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()
Exemplo n.º 47
0
        if mc is not None:
            self.mc = mc
        else:
            mc = MailChimp(settings.MAILCHIMP_KEY)
        threading.Thread.__init__(self)

    def run(self):
        # The actual code we want to run in the tread
        print 'username ', self.user.username
        try: 
            lists = self.mc.lists()
            mc.listSubscribe(
                id=lists[0]['id'],
                email_address=self.user.email,
                merge_vars={'FNAME': self.user.username},
                double_optin=False
                )
        except MailChimpError, e:
            print e.msg
            logger.error(e.msg)

# Signal which starts the subscribe thread
def add_to_mailinglist(sender, user, request, **kwargs):
    SubscribeEmailThread(user, mc).start()


# Create your models here.


user_registered.connect(add_to_mailinglist)
Exemplo n.º 48
0
class UserProfile(models.Model):
#   user = models.ForeignKey(User, unique=True)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
    address = models.CharField(max_length=150, null=True, blank=True)
    locality = models.CharField(max_length=30, null=True, blank=True)
    phone_number = models.PositiveIntegerField(null=True, blank=True)
    description = models.CharField(max_length=150, null=True, blank=True)
    avatar = models.FileField(upload_to="profile_pic", null=True, blank=True) 



def assure_user_profile_exists(pk):
        """
        This might not be working. To be judged later
        """
        user = User.objects.get(pk=pk)
        try:
            # fails if it doesn't exist
            userprofile = user.userprofile
        except UserProfile.DoesNotExist, e:
            userprofile = UserProfile(user=user)
            userprofile.save()
        return

def create_user_profile(**kwargs):
        UserProfile.objects.get_or_create(user=kwargs['user'])

user_registered.connect(create_user_profile)

Exemplo n.º 49
0
    try:
        user_type = request.POST['usertype'].lower()
        if user_type == "teacher":  #user .lower for case insensitive comparison
            Teacher(user=instance).save()
        elif user_type == "student":
            Student(user=instance).save()
        else:
            Profile(user=instance).save(
            )  #Default create - might want to raise error instead
    except KeyError:
        Profile(user=instance).save()  #Default create just a profile


# This callback is called by a registration signal.
# XXX move this function to a meaningful file.
def register_with_profile(sender, user, request, **kwargs):
    profile = Profile(user=user)
    profile.is_human = bool(request.POST["is_human"])
    profile.save()


# This callback is called by a registration signal.
# XXX move this function to a meaningful file.
def register_with_student_profile(sender, user, request, **kwargs):
    profile = Student(user=user)
    profile.save()


# Now a registered user is always a student.
user_registered.connect(register_with_student_profile)
Exemplo n.º 50
0
from django.db import models
from registration.signals import user_registered

class Player(models.Model):
    user = models.OneToOneField('auth.User')
    games_played = models.IntegerField(default=0)
    wins = models.IntegerField(default=0)
    losses = models.IntegerField(default=0)

    def __unicode__(self):
        return self.user.username

def create_player(sender, user, request, **kwargs):
    player = Player()
    player.user = user
    player.save()

user_registered.connect(create_player)
            context)
    subject = "".join(subject.splitlines())
    message = render_to_string(
            settings.REGISTRATION_NOTIFICATION_EMAIL_TEMPLATE_NAME,
            context)

    recipients = []
    if settings.REGISTRATION_NOTIFICATION_ADMINS:
        for userinfo in settings.ADMINS:
            recipients.append(userinfo[1])
    if settings.REGISTRATION_NOTIFICATION_MANAGERS:
        for userinfo in settings.MANAGERS:
            recipients.append(userinfo[1])
    if settings.REGISTRATION_NOTIFICATION_RECIPIENTS:
        method_or_iterable = settings.REGISTRATION_NOTIFICATION_RECIPIENTS
        if callable(method_or_iterable):
            recipients.extend(method_or_iterable())
        elif isinstance(method_or_iterable, (list, tuple)):
            recipients.extend(method_or_iterable)
        else:
            raise ImproperlyConfigured((
                    '``REGISTRATION_NOTIFICATION_RECIPIENTS`` must '
                    'be a list of recipients or function which return '
                    'a list of recipients (Currently the value was "%s")'
                    ) % method_or_iterable)
    # remove duplications
    recipients = frozenset(recipients)

    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipients)
user_registered.connect(send_notification_email_reciver)
Exemplo n.º 52
0
from RIGS.models import Profile
from RIGS.forms import ProfileRegistrationFormUniqueEmail
from registration.signals import user_registered


def user_created(sender, user, request, **kwargs):
    form = ProfileRegistrationFormUniqueEmail(request.POST)
    user.first_name = form.data['first_name']
    user.last_name = form.data['last_name']
    user.initials = form.data['initials']
    # user.phone = form.data['phone']
    user.save()


user_registered.connect(user_created)
Exemplo n.º 53
0
class RegistrationViewUniqueEmail(RegistrationView):
    form_class = RegistrationFormUniqueEmail
    def get_success_url(self, request, user):
        return '/app/'
    

def create_index_page(sender, user, request, **kwargs):
    page = Page.objects.create(title='Index', page_number=1, user=user)


def index(request):
    context = RequestContext(request)
    return render_to_response('index.html', {}, context)


@login_required
def start_app(request):
    context = RequestContext(request)
    return render_to_response('app.html', {}, context)


@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect('index')


# When user is registered, create index page for him
user_registered.connect(create_index_page)
Exemplo n.º 54
0
def asegurar_existencia_perfil_user(pk):
    usuario = Empleado.objects.get(pk=pk)
    try:
        userprofile = usuario.userprofile
    except UserProfile.DoesNotExist, e:
        userprofile = UserProfile(user=usuario)
        userprofile.save()
    return userprofile


def crea_perfil_user(**kwargs):
    UserProfile.objects.get_or_create(user=kwargs['usuario'])


user_registered.connect(crea_perfil_user)


@login_required
def EditUser(request, slug=None):
    """
    Editar usuario de forma simple.
    """
    user = request.user
    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=user)
        if form.is_valid():
            #Actualizar el objeto
            user = form.save()
            messages.success(request,
                             'Usuario actualizado exitosamente.',
Exemplo n.º 55
0
                extra_taxes = float(overrun) * float(tax_rate) / 100

        return extra_taxes


def user_post_save(sender, instance, created, **kwargs):
    if created and not kwargs.get("raw", False):
        address = Address()
        address.save(user=instance)
        profile = UserProfile()
        profile.user = instance
        profile.address = address
        profile.save()

        today = datetime.date.today()
        subscription = Subscription.objects.create(
            owner=instance,
            state=SUBSCRIPTION_STATE_TRIAL,
            expiration_date=today + datetime.timedelta(settings.TRIAL_DURATION),
            transaction_id="TRIAL-%i%i%i-%i" % (today.year, today.month, today.day, instance.id),
        )


def log_registration(sender, user, request, **kwargs):
    logger = logging.getLogger("aemanager")
    logger.info("%s <%s> has registered" % (user.username, user.email))


post_save.connect(user_post_save, sender=User)
user_registered.connect(log_registration)
Exemplo n.º 56
0
    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)
Exemplo n.º 57
0
from django.contrib.auth.models import User, Group

from registration.signals import user_registered

from editor.models import UserRegionalInfo


def create_userregionalinfo(sender, user, request, **kwarg):
    group, created = Group.objects.get_or_create(name='Reporters')
    user.groups.add(group)
    UserRegionalInfo.objects.create(
        user=user,
        phone=request.POST.get('phone', ''),
        information=request.POST.get('information', ''),
    )


user_registered.connect(create_userregionalinfo)