Beispiel #1
0
class SlotOpeningMailListForm(forms.Form):
    volunteers = SelectEmailRecipientField(
        queryset=None,
        required=False,
        widget=forms.SelectMultiple(attrs={
            'type': 'text',
            'class': 'form-control'
        }))

    organizers = SelectEmailRecipientField(
        queryset=None,
        required=False,
        widget=forms.SelectMultiple(attrs={
            'type': 'text',
            'class': 'form-control'
        }))

    volunteer_list = models.User()
    organizer_list = models.User()

    def __init__(self, *args, **kwargs):
        self.volunteer_list = kwargs.pop('volunteers', None)
        self.organizer_list = kwargs.pop('organizers', None)
        super(SlotOpeningMailListForm, self).__init__(*args, **kwargs)
        self.fields['volunteers'].queryset = self.volunteer_list
        self.fields['organizers'].queryset = self.organizer_list

    def clean_volunteers(self):
        volunteers = self.cleaned_data['volunteers']
        return volunteers

    def clean_organizers(self):
        organizers = self.cleaned_data['organizers']
        return organizers
Beispiel #2
0
def provide_sample_data():
    user = auth_models.User(username='******')
    user.save()
    prize_risk_type = models.RiskType(name='prize')
    prize_risk_type.save()
    custom_prize_amount_field = models.CustomField(name='Prize Amount', 
                                                   risk_type=prize_risk_type, 
                                                   format='Currency')
    custom_prize_amount_field.save()
    custom_establishment_name_field = models.CustomField(name='Establishment Name', 
                                                         risk_type=prize_risk_type, 
                                                         format='String')
    custom_establishment_name_field.save()
    account = models.Account(user=user, risk_type=prize_risk_type)
    account.save()
    custom_prize_amount_value = models.CustomValue(custom_field=custom_prize_amount_field, 
                                                    value='1000000.00',
                                                    account=account)
    custom_prize_amount_value.save()
    custom_establishment_name_value = models.CustomValue(custom_field=custom_establishment_name_field, 
                                                         value='New Orleans Casino "Grand Prize"', 
                                                         account=account)
    custom_establishment_name_value.save()
    user = auth_models.User(username='******')
    user.save()
    house_risk_type = models.RiskType(name='house')
    house_risk_type.save()
    custom_address_field = models.CustomField(name='Address',
                                              risk_type=house_risk_type,
                                              format='Address')
    custom_address_field.save()
    custom_phone_number_field = models.CustomField(name='Phone Number',
                                                   risk_type=house_risk_type,
                                                   format='PhoneNumber')
    custom_phone_number_field.save()
    custom_house_type_field = models.CustomField(name='House Type',
                                                 risk_type=house_risk_type,
                                                 format='Enum',
                                                 values='House\n' +
                                                        'Duplex\n' +
                                                        'Apartment\n' +
                                                        'Condominium'
                                                 )
    account = models.Account(user=user, risk_type=house_risk_type)
    account.save()
    custom_address_value = models.CustomValue(custom_field=custom_address_field, 
                                                value='211 Pine Street',
                                                account=account)
    custom_address_value.save()
    custom_phone_number_value = models.CustomValue(custom_field=custom_phone_number_field, 
                                                    value='867 5309', 
                                                    account=account)
    custom_phone_number_value.save()
    custom_house_type_value = models.CustomValue(custom_field=custom_house_type_field,
                                                    value='Apartment',
                                                    account=account)

    
Beispiel #3
0
    def setUp(self):
        self.browser = webdriver.Chrome()
        self.browser.implicitly_wait(3)
        self.browser.wait = WebDriverWait(self.browser, 10)
        activate('en')
        # Create a fixture user
        user = models.User(
            username='******', email='', is_staff=True, is_superuser=True)
        user.set_password('Ma1995.Ma1995.')
        user.save()
        # Creación masiva de catalogo de productos a partir de un archivo CSV
        df = pd.read_csv(f"{os.getcwd()}/app/catalog/catalog_fixture.csv")
        row_items = df.iterrows()

        products = [
            Product(
                name=row["name"],
                link=row["link"],
                classification=row["classification"],
                product_type=row["product_type"],
                brand=row["brand"],
                vendor_link=row["vendor_link"],
                vendor_name=row["vendor_name"],
                vendor_sales=row["vendor_sales"],
                vendor_location=row["vendor_location"],
                )
                for _, row in row_items
                ]
       
        Product.objects.bulk_create(products) #noqa
Beispiel #4
0
    def setUp(self):
        user = user_model.User(username="******",
                               password="******")
        user.save()

        level = Level(flavor='Plain',
                      max_today_reply=1,
                      max_today_write=2,
                      next_level_likes=3,
                      plane_life_span=4)
        level.save()

        next_level = Level(flavor='Strawberry',
                           max_today_reply=1,
                           max_today_write=2,
                           next_level_likes=20,
                           plane_life_span=4)
        next_level.save()

        soy_sauce_level = Level(flavor='SoySauce',
                                max_today_reply=1,
                                max_today_write=2,
                                next_level_likes=3,
                                plane_life_span=4)
        soy_sauce_level.save()

        self.user = User(user=user,
                         today_write_count=10,
                         today_reply_count=10,
                         total_likes=10,
                         level=level)
        self.user.save()
        self.client = Client()
Beispiel #5
0
 def test_ticket_editable_if_enabled_on_tickettype(self):
     user = auth_models.User()
     conference = Conference(tickets_editable=True)
     ticket_type = models.TicketType(allow_editing=True,
                                     conference=conference)
     ticket = models.Ticket(ticket_type=ticket_type, user=user)
     self.assertTrue(ticket.can_be_edited_by(user))
Beispiel #6
0
    def authenticate(self, token=None, type=None):
        user = {}
        if type == 'fb':
            facebook_session = models.FacebookSession.objects.get(
                access_token=token, )
            profile = facebook_session.query('me', type=type)
            try:
                user = auth_models.User.objects.get(username=profile['id'])
            except auth_models.User.DoesNotExist, e:
                user = auth_models.User(username=profile['id'])

            user.set_unusable_password()
            user.email = profile['email']
            user.first_name = profile['first_name']
            user.last_name = profile['last_name']
            user.save()

            url = "http://graph.facebook.com/%s/picture?type=large" % profile[
                "id"]
            avatar = urllib.urlopen(url)
            user.profile.avatar.save(
                slugify(user.username + " social") + '.jpg',
                ContentFile(avatar.read()))

            try:
                models.FacebookSession.objects.get(uid=profile['id']).delete()
            except models.FacebookSession.DoesNotExist, e:
                pass
Beispiel #7
0
def registerUser(request):

    form = RegisterForm(request.POST or None)

    if form.is_valid():

        username = form.cleaned_data.get("username")
        email = form.cleaned_data.get("email")
        first_name = form.cleaned_data.get("first_name")
        last_name = form.cleaned_data.get("last_name")
        password = form.cleaned_data.get("password")

        newUser = models.User(username=username,
                              email=email,
                              first_name=first_name,
                              last_name=last_name)
        newUser.set_password(password)
        newUser.save()

        messages.success(request, "You registered successfully.")
        return redirect("user:login")

    context = {"form": form}

    return render(request, "register.html", context)
Beispiel #8
0
def _make_user_from_registration(reg):
    ## check to see if already registered
    if get_user_by_email(reg.email):
        user = get_user_by_email(reg.email)
        return user

    user = authmodels.User()
    user.username = make_username(reg.email)
    ## intentionally a dupe, since we dont have a username. WE MUST be sure not to overflow it (max_chat is default 30)
    user.email = reg.email
    user.first_name = joeuser_name
    user.set_password(reg.password)
    user.save()

    ## handle couhes reg
    if (reg.couhes):
        ## assert nonblank(reg.first_name) and nonblank(reg.last_name), "Couhes requires non blank first and last names"
        user.first_name = reg.first_name
        user.last_name = reg.last_name
        user.save()
        ## now make couhes consetnform
        cc = CouhesConsent()
        cc.owner = user
        cc.signed_date = reg.when
        cc.save()

    return user
Beispiel #9
0
    def save(self, *args, **kwargs):
        "Form processor"

        profile = None

        if self.invitation:
            # Create DjangoUser
            django_user = django_auth.User(
                username=self.cleaned_data['username'], password='')
            django_user.set_password(self.cleaned_data['password'])
            django_user.save()

            # Crate profile
            try:
                profile = django_user.profile
            except:
                profile = User()
                profile.user = django_user

            profile.name = django_user.username
            profile.default_group = self.invitation.default_group
            profile.save()

            # Create contact
            try:
                contact_type = ContactType.objects.get(
                    Q(name='Person') | Q(slug='person'))
            except:
                contact_type = ContactType.objects.all()[0]

            try:
                # Check if contact has already been created (e.g. by a signals
                contact = profile.get_contact()
                if not contact:
                    contact = Contact()
            except:
                contact = Contact()

            contact.name = self.cleaned_data['name']
            contact.contact_type = contact_type
            contact.related_user = profile
            contact.save()

            # Set email
            try:
                emailfield = contact_type.fields.filter(field_type='email')[0]
                email = ContactValue(
                    value=self.invitation.email, field=emailfield, contact=contact)
                email.save()
            except:
                pass

            # Add quick start widget
            widget = Widget(user=profile,
                            perspective=profile.get_perspective(),
                            module_name='anaf.core',
                            widget_name='widget_welcome')
            widget.save()

        return profile
Beispiel #10
0
 def test_ticket_not_editable_if_disabled_on_conference(self):
     user = auth_models.User()
     conference = Conference(tickets_editable=False)
     ticket_type = models.TicketType(allow_editing=None,
                                     conference=conference)
     ticket = models.Ticket(ticket_type=ticket_type, user=user)
     self.assertFalse(ticket.can_be_edited_by(user))
Beispiel #11
0
    def _import_user_if_not_exists(self, user_data):
        """
        Check if there is a user existing in the
        database, matched by username.
        If not, import the user.
        """
        try:
            mete_user = auth_models.User.objects.get(
                username=user_data['name'])
            print("[i] Updating user: {}".format(user_data['name']))

        except ObjectDoesNotExist:
            print("[i] Creating user: {}".format(user_data['name']))
            # Create new user
            mete_user = auth_models.User(username=user_data['name'])

        # Update userdata
        mete_user.email = user_data['email']
        mete_user.date_joined = user_data['created_at']

        mete_user.save()

        # Update account balance
        account = mete_user.account
        account.balance = user_data['balance']
        account.save()
Beispiel #12
0
def client_registration(request):
    form = client_forms.ClientRegisterForm()
    if request.method == 'POST':
        form = client_forms.ClientRegisterForm(data=request.POST)
        if form.is_valid():
            # print("Form:",dir(form))
            # print("Form:",form.cleaned_data)
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            username = form.cleaned_data.get('user_name')
            email = form.cleaned_data.get('email_id')
            password = make_password(form.cleaned_data.get('password1'))

            user = auth_models.User()
            user.username = username
            user.first_name = first_name
            user.last_name = last_name
            user.email = email
            user.password = password
            user.save()
            return redirect('client_home')

    context = {
        'form': form
    }
    return render(request,
                  'client/client_register.html',
                  context)
Beispiel #13
0
    def authenticate(self,app, **kwargs):
        if app == "facebook":
            access_token = kwargs["access_token"][0]
            expires = kwargs["expires"][0]

            profile = facebook_query_me(access_token,'email,first_name,last_name')
            if 'email' not in profile:
                return None # EMAIL_NOT_FOUND

            try:
                #This user/email exists?
                user = auth_models.User.objects.get(email=profile['email'])

            except auth_models.User.DoesNotExist, e:
                # IF NOT
                # We create a new user
                # Sometimes names are not set in profile
                first_name = 'N/A' or 'first_name' in profile or profile['first_name']
                last_name = 'N/A' or 'last_name' in profile or profile['last_name']
                # We copy user data from their profile
                user = auth_models.User(username=profile['email'], email=profile['email'], is_active=True, first_name = first_name, last_name= last_name)
                user.set_unusable_password()
                user.save()

            user_profile, created = UserProfile.objects.get_or_create(user=user)
            user_profile.facebook_uid = profile['id']
            user_profile.save()


            #Renew or create facbook session
            try:
                FacebookSession.objects.get(user=user).delete()
            except FacebookSession.DoesNotExist, e:
                pass
Beispiel #14
0
 def setUp(self):
     self.user = auth_models.User(username="******", password="******")
     self.blog_post = BlogPost(
         blog_title="",
         blog_slug="",
         blog_text="",
         blog_summary="",
         pub_date=datetime(2021, 1, 2),
     )
Beispiel #15
0
 def test_ticket_not_editable_if_time_over_on_conference(self):
     user = auth_models.User()
     now = datetime.datetime.now()
     conference = Conference(tickets_editable=True,
                             tickets_editable_until=now +
                             datetime.timedelta(days=-1))
     ticket_type = models.TicketType(allow_editing=True,
                                     conference=conference)
     ticket = models.Ticket(ticket_type=ticket_type, user=user)
     self.assertFalse(ticket.can_be_edited_by(user, current_time=now))
Beispiel #16
0
    def authenticate(self, token=None):
        facebook_session = models.FacebookSession.objects.get(
            access_token=token, )

        profile = facebook_session.query('me')

        try:
            user = auth_models.User.objects.get(username=profile['id'])
        except auth_models.User.DoesNotExist, e:
            user = auth_models.User(username=profile['id'])
Beispiel #17
0
def createsuperusers():
    """
    Creates all superusers defined in settings.INITIAL_SUPERUSERS.
    These superusers do not have any circles. They are plain superusers.
    However you may want to signup yourself and make this new user a super user then.
    """
    from django.contrib.auth import models as auth_models
    from django.conf import settings
    from django.core.mail import send_mail
    from django.contrib.sites import models as site_models
    import uuid
    from django.db import transaction
    from django.db.models import Q

    site = site_models.Site.objects.get(id=settings.SITE_ID)

    for entry in settings.INITIAL_SUPERUSERS:
        # create initial supersuers.

        print('*** Create specified superuser {}'.format(entry['username']))

        if not auth_models.User.objects.filter(
                Q(username__in=[entry['username'], entry['email']])
                | Q(email=entry['email'])).exists():
            # create the superuser if it does not exist yet
            with transaction.atomic():
                password = ''.join(str(uuid.uuid4())[:8])

                root = auth_models.User()
                root.first_name = entry.get('first_name', '')
                root.last_name = entry.get('last_name', '')
                root.email = entry['email']
                root.username = entry['username']
                root.set_password(password)
                root.is_active = True
                root.save()
                # overwrite default is_staff
                root.is_staff = True
                root.is_superuser = True
                root.save()

                send_mail(
                    subject='Your superuser account',
                    recipient_list=[entry['email']],
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    message='username: {username}\npassword: {pw}\nsite: {site}'
                    .format(username=root.username,
                            pw=password,
                            site=site.domain),
                )

                print('\tA new superuser was created. Check {}'.format(
                    entry['email']))
        else:
            print('\tSpecified superuser already exists')
 def test_report_bad_permission(self):
     anotherTestUser = authModels.User(username="******",
                                       password=make_password("password"))
     anotherTestUser.is_staff = True
     anotherTestUser.save()
     self.assertTrue(
         self.client.login(username="******", password="******"))
     response = self.client.get(reverse('history-report'), follow=True)
     SimpleTestCase.assertRedirects(self,
                                    response=response,
                                    expected_url="/admin/")
Beispiel #19
0
 def authenticate(self, ticket=None, service=None):
     username = auth_ticket(ticket, service)
     if not username:
         return None
     i_user = list(models.User.objects.filter(username=username))
     if not i_user:
         uic_user = server.getUserByUsername(arg0=username)
         if hasattr(uic_user, 'username'):
             new_user = models.User(username=uic_user.username,
                                    email=uic_user.email)
             new_user.save()
             return new_user
         return None
     return i_user[0]
 def setUp(self):
     self.testUser = authModels.User(username="******",
                                     password=make_password("password"))
     self.testUser.is_staff = True
     self.testUser.save()
     self.approver_group = authModels.Group.objects.get(name="approver")
     self.testUser.groups.add(self.approver_group)
     self.state1 = State.objects.get(slug="needs-approval")
     self.user1 = User.objects.get(pk=1)
     self.group1 = Group.objects.get(pk=1)
     self.group2 = Group.objects.get(pk=2)
     self.grant1 = Grant.objects.create(group_id=self.group1.id,
                                        user_id=self.user1.id,
                                        status=self.state1)
Beispiel #21
0
def signup(request):
    if request.method == "POST":
        register_form = forms.SignUpform(request.POST)
        if register_form.is_valid():  # 表格要全寫才叫vaild
            username = register_form.cleaned_data['username']
            email = register_form.cleaned_data['email']
            password = register_form.cleaned_data['password']
            password2 = register_form.cleaned_data['password2']

            if password != password2:
                messages.error(request, '請檢查密碼是否輸入正確')
                return render(request, 'chat/signup.html', locals())
            if len(password) < 8:
                messages.error(request, '密碼長度需至少8個字元')
                return render(request, 'chat/signup.html', locals())

            else:
                if len(username) >= 20:
                    messages.error(request, 'username 長度請小於20')
                    return render(request, 'chat/signup.html', locals())
                same_name_user = models.User.objects.filter(username=username)
                if same_name_user:
                    messages.error(request, '用戶已經存在,請更換')
                    return render(request, 'chat/signup.html', locals())
                same_email = models.User.objects.filter(email=email)
                if same_email:
                    messages.error(request, '該信箱已經註冊過,請更換')
                    return render(request, 'chat/signup.html', locals())

                new_user = models.User()
                new_user.username = username
                # new_user.password = password
                new_user.password = make_password(password)
                new_user.email = email
                new_user.save()
                print('Sign up Done')

                if request.POST.get('username'):
                    un = Personal()
                    un.username = request.POST.get('username')

                    pid = str(uuid4())
                    personal_id = pid.split('-')[4]
                    un.personal_ID = personal_id
                    un.save()
                return redirect('/dna')

    register_form = forms.SignUpform()
    return render(request, 'chat/signup.html', {})
Beispiel #22
0
def import_users():

    DU.User.objects.all().exclude(username="******").delete()
    oldusers = L.Usuarios.objects.all()

    for olduser in oldusers:

        user = DU.User(id=hack_for_user_id(olduser.id),
                       first_name=olduser.nombre[:30],
                       last_name=olduser.apellido[:30],
                       username=olduser.user[:30],
                       email=olduser.email)
        user.set_password(olduser.pais)
        user.save()
        user.groups.add(1)
    def create(self, validated_data: dict) -> auth_models.User:
        """Create the user instance

		Args:
		    validated_data: The validated serializer data

		Returns:
		    A django auth user instance
		"""
        # Pop the password so we can set it later
        password = validated_data.pop('password')

        # Create a user instance
        user_instance = auth_models.User(**validated_data)
        user_instance.set_password(password)
        user_instance.save()

        return user_instance
Beispiel #24
0
 def save(self, *args, **kwargs):
     "Form processor"
     
     if self.instance.id:
         self.instance.user.username = self.instance.name
         self.instance.user.save()
         super(UserForm, self).save(*args, **kwargs)
     else:
         new_user = django_auth.User(username=self.cleaned_data['name'], password='')
         new_user.set_password(self.cleaned_data['password'])
         new_user.save()
         self.instance.user = new_user
         super(UserForm, self).save(*args, **kwargs)
     
     if self.cleaned_data['perspective']:
         self.instance.set_perspective(self.cleaned_data['perspective'])
     
     return self.instance
Beispiel #25
0
    def test_insure_the_grand_prize(self):
        user = auth_models.User(username='******')
        user.save()
        prize_risk_type = models.RiskType(name='prize')
        prize_risk_type.save()
        custom_prize_amount_field = models.CustomField(
            name='Prize Amount', risk_type=prize_risk_type, format='Currency')
        custom_prize_amount_field.save()
        self.assertTrue(custom_prize_amount_field.validate('1'))
        self.assertTrue(custom_prize_amount_field.validate('10.00'))
        self.assertFalse(custom_prize_amount_field.validate('not a number'))
        custom_establishment_name_field = models.CustomField(
            name='Establishment Name',
            risk_type=prize_risk_type,
            format='String')
        custom_establishment_name_field.save()
        self.assertTrue(
            custom_establishment_name_field.validate('Moulin Rouge'))
        self.assertFalse(custom_establishment_name_field.validate(''))
        account = models.Account(user=user, risk_type=prize_risk_type)
        account.save()
        custom_prize_amount_value = models.CustomValue(
            custom_field=custom_prize_amount_field,
            value='1000000.00',
            account=account)
        custom_prize_amount_value.save()
        custom_establishment_name_value = models.CustomValue(
            custom_field=custom_establishment_name_field,
            value='New Orleans Casino "Grand Prize"',
            account=account)
        custom_establishment_name_value.save()

        #  Note:  The <input> fields all need name attributes.

        self.assertEqual(
            '<input value="1000000.00" type="number" min="0" step="0.01">',
            custom_prize_amount_value.edit())
        self.assertEqual('1000000.00', custom_prize_amount_value.display())
        self.assertEqual(
            '<input value="New Orleans Casino &quot;Grand Prize&quot;" type="text">',
            custom_establishment_name_value.edit())
        self.assertEqual('New Orleans Casino &quot;Grand Prize&quot;',
                         custom_establishment_name_value.display())
Beispiel #26
0
class NewChatEntryForm(forms.Form):

    description = forms.CharField(label='Description',
                                  widget=forms.Textarea(
                                      attrs={
                                          'type': 'text',
                                          'class': 'form-control',
                                          'rows': 2,
                                          'style': 'resize:none;'
                                      }))

    user = models.User()
    datetime = get_dt()
    parentGroup = models.Group()

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        self.parentGroup = kwargs.pop('parentGroup')
        super(NewChatEntryForm, self).__init__(*args, **kwargs)

    def clean_user(self):
        user = self.cleaned_data['user']
        return user

    def clean_description(self):
        description = self.cleaned_data['description']
        return description

    def clean_datetime(self):
        datetime = self.cleaned_data['datetime']
        return datetime

    def clean_parentGroup(self):
        parentGroup = self.cleaned_data['parentGroup']
        return parentGroup

    def save(self, commit=True):
        entry = Chat_Entry(user=self.user,
                           parentGroup=self.parentGroup,
                           description=self.cleaned_data['description'],
                           datetime=self.datetime)
        return entry
Beispiel #27
0
    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        new_user = auth.User(
            email=validated_data['email'],
            username=validated_data['username'],
            password=validated_data['password'],
        )

        new_user.set_password(new_user.password)
        new_user.save()

        for group in validated_data['groups']:
            my_group = Group.objects.get(name=group)
            new_user.groups.add(my_group)
            new_user.save()
        # my_group.user_set.add(new_user)
        # my_group.save()
        return new_user
Beispiel #28
0
    def authenticate(self, token=None):

        facebook_session = models.FacebookSession.objects.get(
            access_token=token,
        )

        profile = facebook_session.query('me')

        try:
            user = auth_models.User.objects.get(username=profile['id'])
        except auth_models.User.DoesNotExist, e:
            user = auth_models.User(username=profile['id'])



            user.set_unusable_password()
            user.email = profile['email']
            user.first_name = profile['first_name']
            user.last_name = profile['last_name']
            password = self.password_generate()
            user.set_password(password)

            user.email_user("Registrado en libreta", 'your username:'******'\n'+'your password:'******'hometown']['name']
            new_profile.facebook_url = profile['link']
            new_profile.save(using=self._db)

            for perm in PERMISSIONS['profile']:
                assign(perm, user, new_profile)

            for perm in PERMISSIONS['user']:
                assign(perm, user, user)

            try:
                models.FacebookSession.objects.get(uid=profile['id']).delete()
            except models.FacebookSession.DoesNotExist, e:
                pass
Beispiel #29
0
    def save(self, *args, **kwargs):
        "Form processor"

        if self.instance.id:
            self.instance.user.username = self.instance.name
            self.instance.user.save()
            super(UserForm, self).save(*args, **kwargs)
        else:
            new_user = django_auth.User(username=self.cleaned_data['name'],
                                        password='')
            new_user.set_password(self.cleaned_data['password'])
            models.signals.post_save.disconnect(user_autocreate_handler,
                                                sender=django_auth.User)
            new_user.save()
            if settings.ANAF_SIGNALS_AUTOCREATE_USER:
                models.signals.post_save.connect(user_autocreate_handler,
                                                 sender=django_auth.User)
            self.instance.user = new_user
            super(UserForm, self).save(*args, **kwargs)

        if self.cleaned_data['perspective']:
            self.instance.set_perspective(self.cleaned_data['perspective'])

        return self.instance
Beispiel #30
0
    def create_with_user(cls,
                         school,
                         name='',
                         email=None,
                         phone=None,
                         password=None,
                         role='',
                         school_staff=False,
                         is_active=False,
                         email_notifications=True,
                         **kwargs):
        """
        Create a Profile and associated User and return the new Profile.

        Generates a unique username to satisfy the User model by hashing as
        much user data as we're given, plus a timestamp.

        """
        to_hash = u"-".join(
            [email or u'', phone or u'', name,
             u'%f' % time.time()])
        username = base64.b64encode(sha1(to_hash.encode('utf-8')).digest())
        now = timezone.now()
        user = auth_models.User(
            username=username,
            email=email,
            is_staff=False,
            is_active=is_active,
            is_superuser=False,
            date_joined=now,
        )
        user.set_password(password)
        user.save()
        code = generate_code(username, 6) if school_staff else None
        kwargs.update({
            'school': school,
            'name': name,
            'phone': phone,
            'user': user,
            'role': role,
            'school_staff': school_staff,
            'code': code,
        })

        kwargs.setdefault(
            'country_code',
            kwargs['invited_by'].country_code
            if 'invited_by' in kwargs else settings.DEFAULT_COUNTRY_CODE,
        )

        kwargs.setdefault(
            'source_phone',
            settings.PORTFOLIYO_NUMBERS.get(kwargs['country_code'],
                                            settings.DEFAULT_NUMBER))

        for pref in cls.NOTIFICATION_PREFS:
            kwargs[pref] = email_notifications
        profile = cls(**kwargs)

        # try a few times to generate a unique code, if we keep failing give up
        # and raise the error
        for i in range(5):
            sid = transaction.savepoint()
            try:
                profile.save()
            except IntegrityError:
                if code is not None:
                    transaction.savepoint_rollback(sid)
                    profile.code = generate_code(u'%s%s' % (username, i), 6)
                else:
                    raise
            else:
                break
        else:
            # give up and try one last save without catching errors
            profile.save()

        return profile