Exemple #1
0
    def test_userprofile_without_required_fields_is_invalid(self):

        no_user_model = UserProfile(
            user=None,
            date_of_birth=self.valid_dob,
            bio=self.valid_bio
        )

        no_dob_model = UserProfile(
            user=self.valid_user,
            date_of_birth=None,
            bio=self.valid_bio
        )

        second_valid_user = User.objects.create(email="*****@*****.**")
        no_bio_model = UserProfile(
            user=second_valid_user,
            date_of_birth=self.valid_dob,
            bio=None
        )

        for model in [
            no_user_model,
            no_dob_model,
            no_bio_model,
        ]:
            with self.assertRaises(IntegrityError):
                model.save()
Exemple #2
0
    def test_create_profile(self):
        from accounts.models import UserProfile
        assert not hasattr(self.user, 'userprofile')

        valid_data = {
            'user': self.user,
            "year_of_admission": 2000,
            "department": "cs"
        }
        invalid_data = [{
            'user': self.user,
            "year_of_admission": 1000,
            "department": "cs"
        }, {
            "year_of_admission": 1000,
            "department": "cs"
        }]

        profile = UserProfile(**valid_data)

        # year of admission must be in (1800 ~ 2500)
        for data in invalid_data:
            with self.assertRaises(ValidationError):
                UserProfile(**data).save()

        profile.save()

        assert hasattr(self.user, 'userprofile')
        self.assertEqual(self.user.username, profile.username)
 def setUp(self):
     form = ChopRegistrationForm(self.test_user)
     form.save()
     # Manually create existing user with profile.
     existing_user = User(**self.existing_user)
     existing_user.set_password(self.existing_user['password'])
     existing_user.save()
     UserProfile(user=existing_user).save()
     test_user = User.objects.get(email=self.test_user['email'])
     UserProfile(user=test_user).save()
Exemple #4
0
def create_user_from_weibo(request,
                           template_name='register/create_user_from_weibo.html'
                           ):

    oauth_access_token = request.session.get('oauth_access_token', None)

    if request.user.is_authenticated() or oauth_access_token is None:
        return HttpResponseRedirect(reverse('home.views.index'))

    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=_get_weibo_callback_url(request))
    client.set_access_token(oauth_access_token['access_token'],
                            oauth_access_token['expires_in'])

    weibo_user = client.get.users__show(uid=oauth_access_token['uid'])
    weibo_username = weibo_user.screen_name

    template_var = {}
    form = RegistrationForm(initial={'username': weibo_username})
    if request.method == 'POST':
        form = RegistrationForm(request.POST.copy())
        if request.method == 'POST':
            if form.is_valid():
                username = form.cleaned_data['username']
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']
                user = User.objects.create_user(username, email, password)
                user.is_active = True
                user.save()

                profile = UserProfile()
                profile.user = user
                profile.song_ord_filed = 'post_datetime'
                profile.save()

                #weibo信息记录
                w_user = WeiboUser()
                w_user.user = user

                w_user.weibo_user_id = oauth_access_token['uid']
                w_user.weibo_username = weibo_username
                w_user.oauth_access_token = oauth_access_token['access_token']
                w_user.save()

                #发微博提示
                if request.POST.get('update_msg'):
                    msg = request.POST.get('bind_msg')[0:140]
                    client.post.statuses__update(status=msg)

                user = authenticate(username=username, password=password)
                auth_login(request, user)

                return HttpResponseRedirect(reverse('songs.views.my_home'))

    template_var['form'] = form
    template_var['weibo_username'] = weibo_username
    return render_to_response(template_name,
                              template_var,
                              context_instance=RequestContext(request))
Exemple #5
0
def signup_user(request):
    if request.method == 'GET':
        context = {
            'form': SignUpForm(),
        }

        return render(request, 'accounts/signup', context)
    else:
        form = SignUpForm(request.POST)

        if form.is_valid():
            user = form.save()
            profile = UserProfile(
                user=user,

            )
            profile.save()

            login(request, user)
            return redirect('index')

        context = {
            'form': form,
        }

        return render(request, 'accounts/signup.html', context)
Exemple #6
0
 def delete(self, request, user_pk, format=None):
     profile = self.get_object(user_pk)
     self.delete_profile_picture_from_storage(profile=profile)
     # Restore default profile picture
     profile.profile_picture = UserProfile().profile_picture
     profile.save()
     return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #7
0
    def save(self):
        user = User(
            email=self.validated_data['email'],
            username=self.validated_data['username'],
            first_name=self.validated_data['first_name'],
            last_name=self.validated_data['last_name'],
        )

        password = self.validated_data['password']
        password2 = self.validated_data['password2']

        if password != password2:
            raise serializers.ValidationError(
                {"Password": "******"})

        user.set_password(password)

        user.save()

        phone = self.validated_data['phone']
        photo = self.validated_data['photo']
        is_tutor = self.validated_data['is_tutor']

        profile = UserProfile(user=user,
                              phone=phone,
                              photo=photo,
                              is_tutor=is_tutor)
        profile.save()

        return user
Exemple #8
0
    def form_valid(self, form):
        user = form.save()
        if user.user_profile is None:
            profile = UserProfile(user=user)
        else:
            profile = user.user_profile
        gender = form.cleaned_data.get('gender')
        if gender is not None and not 'x' in gender:
            profile.gender = gender
        profile.send_newsletters = form.cleaned_data.get(
            'marketing_optin') != 'false'
        profile.activation_key = profile.generate_activation_key()
        profile.detected_country = self.request.country
        profile.preferred_currency = self.request.session.get(
            'preferred_currency', '')
        profile.save()

        Events(self.request).user_signup(user)

        # login user
        password = form.cleaned_data.get('password')
        user = authenticate(username=user.username, password=password)
        login(self.request, user)
        messages.success(self.request, REGISTER_SUCCESS_MESSAGE)
        return render(self.request,
                      "mailing_lists/fragments/capture_complete.html")
Exemple #9
0
    def save(self):
        """
        Override the save method to create a custom profile for the user.
        """
        # All username names should be lower-case.
        self.cleaned_data['username'] = self.cleaned_data['username'].lower()

        # Save the parent form and get the user
        new_user = super(CustomSignupForm, self).save()

        # Remove the profile that's automatically created by Userena
        new_user.profile.delete()

        new_user.profile = UserProfile(
            ar_first_name=self.cleaned_data['ar_first_name'],
            ar_middle_name=self.cleaned_data['ar_middle_name'],
            ar_last_name=self.cleaned_data['ar_last_name'],
            en_first_name=self.cleaned_data['en_first_name'],
            en_middle_name=self.cleaned_data['en_middle_name'],
            en_last_name=self.cleaned_data['en_last_name'],
            mobile=self.cleaned_data['mobile'],
            state=State.objects.get(pk=self.cleaned_data['state']),
            university=self.cleaned_data['university'],
            academic_year=self.cleaned_data['academic_year'],
            specialty=self.cleaned_data['specialty'],
        )

        new_user.profile.save()

        return new_user
Exemple #10
0
    def create(self, validated_data):
        profile_data = validated_data.pop('profile', None)
        username = validated_data['username']
        email = validated_data['email']
        password = validated_data['password']
        user = User(
                username = username,
                email = email
        )
        user.set_password(password)
        user.save()

        avatar = profile_data.get('avatar') or None
        if not avatar:
            avatar = 'https://api.adorable.io/avatar/200/' + username
        profile = UserProfile(
            user = user,
            bio = profile_data.get('bio', ''),
            license = profile_data.get('license', ''),
            avatar = avatar,
            name = profile_data.get('name', ''),
            status = profile_data.get('status', 'Member')
        )
        profile.save()
        return user
Exemple #11
0
def persist_pet(request, pet, template_name):
    user = request.user.id
    if request.method == 'GET':
        pet.user_id = UserProfile(user)
        form = PetForm(instance=pet)
        context = {
            'form': form,
            'pet': pet,
        }
        return render(request, f'{template_name}.html', context)
    else:
        old_image = pet.image
        form = PetForm(
            request.POST,
            request.FILES,
            instance=pet,
        )
        if form.is_valid():
            if old_image:
                clean_up_files(old_image.path)
            form.save()
            Like.objects.filter(pet_id=pet.id).delete()
            return redirect('pet details or comment', pet.pk)
        context = {
            'form': form,
            'pet': pet,
        }
        return render(request, f'{template_name}.html', context)
Exemple #12
0
 def testValidPostalAddresses(self):
     # Must not raise exception
     up = UserProfile(**self.f_fixture)
     self.assertEqual(self.f_postal_address['address'],
                      up.postal_address.address)
     self.assertEqual(self.f_postal_address['address'],
                      up.delivery_address.address)
Exemple #13
0
    def test_can_create_read_update_userprofile(self):
        # test that user can create userProfile
        userprofile = UserProfile(user=self.user,
                                  country=2,
                                  location=84,
                                  occupation='Developer',
                                  phonenumber='08020202020',
                                  intlnumber='+12334567789')
        userprofile.save()
        self.assertNotEqual(UserProfile.objects.count(), 0)

        # test that a userprofile record has been added
        userprofile = UserProfile.objects.get(id=userprofile.id)
        self.assertIsNotNone(userprofile.id)

        # update a userprofile record
        new_occupation = "Architect"
        another_userprofile = UserProfile.objects.get(id=userprofile.id)
        another_userprofile.occupation = new_occupation
        another_userprofile.save()

        # test that update has taken effect
        another_userprofile = UserProfile.objects.get(id=userprofile.id)
        self.assertEquals(another_userprofile.occupation, new_occupation)

        # delete a userprofile record
        another_userprofile = UserProfile.objects.get(id=userprofile.id)
        UserProfile.delete(another_userprofile)
        with self.assertRaises(UserProfile.DoesNotExist) as context:
            UserProfile.objects.get(id=userprofile.id)
        self.assertTrue("does not exist" in context.exception.message)
Exemple #14
0
    def test_boughtItem_model_works_well(self):
        item_yes = ItemList.objects.create(name="餅乾", price=10, remain=10)
        a = UserProfile(user=self.user, usable_points=100, history_points=100)
        a.save()

        response = self.client.get('/shop/b04202048/' + str(item_yes.pk) + '/')
        b = BoughtItems.objects.filter(user=self.user).count()
        self.assertEqual(b, 1)

        response = self.client.get('/shop/b04202048/' + str(item_yes.pk) + '/')
        c = BoughtItems.objects.filter(user=self.user).count()
        self.assertEqual(c, 1)
        c1 = BoughtItems.objects.get(user=self.user)
        self.assertEqual(c1.item_quantity, 2)

        d = BoughtItems.objects.get(user=self.user)
        d.has_redeemed = True
        d.save()

        response = self.client.get('/shop/b04202048/' + str(item_yes.pk) + '/')

        e = BoughtItems.objects.filter(user=self.user).count()
        self.assertNotEqual(e, 1)

        response = self.client.get('/shop/b04202048/' + str(item_yes.pk) + '/')
        f = BoughtItems.objects.filter(user=self.user).filter(
            has_redeemed=False)
        self.assertEqual(f[0].item_quantity, 2)
Exemple #15
0
    def test_buy_more_than_maximun(self):
        item_yes = ItemList.objects.create(name="餅乾",
                                           price=10,
                                           remain=10,
                                           max_per_person=2)
        a = UserProfile(user=self.user, usable_points=100, history_points=100)
        a.save()

        response = self.client.get('/shop/b04202048/' + str(item_yes.pk) + '/')
        self.assertIn(str('購買成功').encode(), response.content)
        response1 = self.client.get('/shop/b04202048/' + str(item_yes.pk) +
                                    '/')
        self.assertIn(str('購買成功').encode(), response1.content)
        b = BoughtItems.objects.get(user=self.user)
        self.assertEqual(b.item_quantity, 2)

        response2 = self.client.get('/shop/b04202048/' + str(item_yes.pk) +
                                    '/')
        self.assertIn(
            str('很抱歉!您已超過此項目購買上限!請選購其他商品').encode(), response2.content)

        response3 = self.client.get('/shop/b04202048/' + str(item_yes.pk) +
                                    '/')
        self.assertIn(
            str('很抱歉!您已超過此項目購買上限!請選購其他商品').encode(), response3.content)
Exemple #16
0
    def get(self, request: HttpRequest) -> JsonResponse:
        """
        Return the current profile data, as json
        :param request: GET request to get the profile data
        :type request: HttpRequest
        :return: current profile details for the user
        :rtype: JsonResponse
        """
        # First check if the user has a profile configured, or else create a new profile
        try:
            p = self.request.user.userprofile
        except ObjectDoesNotExist:
            request.user.userprofile = UserProfile()
            p = request.user.userprofile
        data = dict()
        data['first_name'] = request.user.first_name
        data['last_name'] = request.user.last_name
        data['gender'] = p.gender
        data['phone'] = p.phone

        data['is_seller'] = bool(request.user.groups.filter(name='Merchant'))

        if data['is_seller']:
            data['store_name'] = request.user.sellerprofile.store_name
            data['address'] = request.user.sellerprofile.address
            data['pincode'] = request.user.sellerprofile.pincode

        return JsonResponse(data, status=200)
Exemple #17
0
def _profile(user):
    """
    Create an User Profile
    """
    profile = UserProfile()
    profile.user_id = user.id
    profile.save()
Exemple #18
0
	def create(self, validated_data):
		# Create User
		user_obj = User.objects.create(**validated_data['user'])
		user_obj.set_password(validated_data['user']['password'])
		user_obj.save()

		# Create Address
		address_obj = Address.objects.create(**validated_data['address'])

		# Create User Profile
		club_name = validated_data['football_club']["club"]
		football_club = FootballClub.objects.get(club=club_name)
		# football_club = validated_data['football_club']

		gender = validated_data['gender']
		birth_date = validated_data['birth_date']
		weight = validated_data['weight']
		# photo = validated_data['photo']

		profile_obj = UserProfile(
					user = user_obj,
					address = address_obj,
					football_club = football_club,
					gender = gender,
					birth_date = birth_date,
					weight = weight,
					# photo = photo,
					allowed_club_change = True,
					total_points = 0
					)
		profile_obj.save()
		return validated_data
Exemple #19
0
def register(request):
    if request.user != None and request.user.is_authenticated():
        return redirect('/')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            #Create the user
            email = form.cleaned_data.get('email')
            passwd = form.cleaned_data.get('password1')

            user = User(email=email)
            user.set_password(passwd)
            user.save()
            user.username = user.pk
            user.save()
            user_profile = UserProfile(user=user)
            user_profile.save()
            user.backend = 'user_backends.email_username.EmailOrUsernameModelBackend'

            #logs the new user
            login(request, user)
            return redirect('/')
    else:
        form = RegistrationForm()

    return locals()
 def form_valid(self, form):
     valid = super().form_valid(form)
     user = form.save()
     profile = UserProfile(user=user)
     profile.save()
     login(self.request, user)
     return valid
def register(request):
    print('Hello')
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        print('Hello')

        if form.is_valid():
            objuser = form.save()

            print(objuser.id)
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')

            print(request.user.id)

            objt = UserProfile(user=objuser,
                               UID=request.POST.get('UID'),
                               branch=request.POST.get('Branch'),
                               year=request.POST.get('Year'),
                               contactno=request.POST.get('ContactNo'))

            print(objt)

            objt.save()

            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('http://127.0.0.1:8000/accounts')

    else:
        form = SignUpForm()

    print('Hello')
    return render(request, 'accounts/signup.html', {'form': form})
Exemple #22
0
    def test_buy(self):

        item_no = ItemList.objects.create(name="蛋糕", price=10, remain=0)
        item_yes = ItemList.objects.create(name="餅乾", price=10, remain=10)

        a = UserProfile(user=self.user, usable_points=100, history_points=100)
        a.save()

        self.assertEqual(a.user, self.user)
        self.assertEqual(a.usable_points, 100)
        self.assertEqual(a.history_points, 100)

        response = self.client.get('/shop/b04202048/' + str(item_yes.pk) + '/')

        b = UserProfile.objects.get(user=self.user)
        self.assertEqual(b.usable_points, 90)
        self.assertEqual(b.history_points, 100)

        item_yes_final = ItemList.objects.get(name=item_yes.name)

        c = BoughtItems.objects.count()
        d = BoughtRecord.objects.count()

        self.assertNotEqual(c, 0)
        self.assertNotEqual(d, 0)

        response2 = self.client.get('/shop/b04202048/' + str(item_yes.pk) +
                                    '/')
        e = BoughtItems.objects.get(user=self.user)
        self.assertEqual(e.item_quantity, 2)

        response3 = self.client.get('/shop/b04202048/4/')
        self.assertIn(str('物品不存在').encode(), response3.content)
        self.assertEqual(item_yes_final.remain, 9)
        self.assertEqual(response.status_code, 200)
Exemple #23
0
    def test_not_enough_money(self):
        item = ItemList.objects.create(name="蛋糕", price=10, remain=2)

        a = UserProfile(user=self.user, usable_points=5)
        a.save()

        response = self.client.get('/shop/b04202048/' + str(item.pk) + '/')
        self.assertIn(str('您的點數不足').encode(), response.content)
def retrieve(request):
    ''' note that this requires an authenticated user before we try calling it '''
    try:
        profile = request.user.get_profile()
    except UserProfile.DoesNotExist:
        profile = UserProfile(user=request.user)
        profile.save()
    return profile
Exemple #25
0
 def testBlankBirthDate(self):
     """
     Must raise ValidationError.
     """
     f = self.__copyFixture()
     f['birth_date'] = ''
     with self.assertRaises(ValidationError):
         UserProfile(**f)
Exemple #26
0
def add(request):
    if request.method == 'POST':
        user = UserProfile(username=request.POST.get('username'),
                           birthday=request.POST.get('birthday'))
        user.save()

        return redirect('/')

    return render(request, 'accounts/add.html')
Exemple #27
0
    def create_inactive_user(self,
                             name,
                             email,
                             password,
                             site='',
                             send_email=True):
        """
        Creates a new User and a new ActionRecord for that
        User, generates an activation key, and mails it.

        Pass ``send_email=False`` to disable sending the email.

        You can disable email_sending in settings: DISABLE_REGISTRATION_EMAIL=True

        """
        send_email = not getattr(settings, 'DISABLE_REGISTRATION_EMAIL', False)

        # Create the user.
        new_user = User(username=email.replace('@', '-'),
                        email=email,
                        first_name=name)
        new_user.set_password(password)
        new_user.is_active = False
        new_user.save()

        from accounts.models import UserProfile
        UserProfile(user=new_user, site=site).save()

        # Generate a salted SHA1 hash to use as a key.
        salt = sha.new(str(random.random())).hexdigest()[:5]
        action_key = sha.new(salt + slugify(new_user.email)).hexdigest()

        # And finally create the record.
        new_record = self.create(user=new_user,
                                 action_key=action_key,
                                 type='A')
        if send_email:
            current_domain = Site.objects.get_current().domain
            subject = "Activate your new account at %s" % current_domain
            message_template = loader.get_template(
                'accounts/activation_email.txt')
            message_context = Context({
                'site_url':
                '%s://%s' % (settings.SITE_PROTOCOL, current_domain),
                'action_key':
                action_key,
                'expiration_days':
                settings.ACTION_RECORD_DAYS,
                'password':
                password,
                'user':
                new_user
            })
            message = message_template.render(message_context)
            new_user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        return new_user
Exemple #28
0
    def testTooYoungClient(self):
        f = self.__copyFixture()
        f['birth_date'] = "%d-01-01" % datetime.date.today().year
        # Must raise exception
        with self.assertRaises(ValidationError) as cm:
            up = UserProfile(**f)
            up.full_clean()

        err = cm.exception
        self.assertIn(_(u"You must be min"), err.messages[0])
 def form_valid(self, form):
     user = form.save(commit=False)
     userprofile = UserProfile(
         user=user,
         telephone_number=form.cleaned_data['phone_number'],
         email=form.cleaned_data['email'])
     user.save()
     userprofile.save()
     login(self.request, user)
     return redirect('home page')
Exemple #30
0
def retrieve(request):
    """ note that this requires an authenticated user before we try calling it """
    try:
        profile = request.user.userprofile
        print(profile)
    except UserProfile.DoesNotExist:
        profile = UserProfile(user=request.user)
        print(profile)
        profile.save()
    return profile