Пример #1
0
    def post_save(self, obj, created=False):
        create = False
        if self.request.method == 'POST':
            create = True
            profile = Profile(user=obj)
            profile.save()
            token = ActivationToken(user=obj,
                                    token=core.utils.gen_temporary_token())
            token.save()
            subject, message = registration_message(token)
            send_mail(subject,
                      message,
                      '*****@*****.**',
                      [obj.email],
                      fail_silently=False)
            # First community registration
            if LocalCommunity.objects.filter(name=settings.INITIAL_COMMUNITY).exists():
                community = LocalCommunity.objects.get(name=settings.INITIAL_COMMUNITY)
                Member.objects.create(user=obj, community=community, role="2", status="1")

        LogEntry.objects.log_action(user_id=obj.id,
                                    content_type_id=ContentType.objects.get_for_model(self.model).pk,
                                    object_id=obj.id,
                                    object_repr=obj.email,
                                    action_flag=ADDITION if create else CHANGE)
Пример #2
0
def pythonistas_signup(request):
    context = {}
    context["new_job_form"] = JobForm

    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            profile = Profile(
                user=user,
                github=form.cleaned_data["github"],
                linkedin=form.cleaned_data["linkedin"],
                portfolio=form.cleaned_data["portfolio"],
                cellphone=form.cleaned_data["cellphone"],
            )
            profile.save()
            login(request, user)
            return redirect("/")
        else:
            context["form"] = form
            return render(request, "pythonistas-signup.html", context)
    else:
        form = RegisterForm()
        context["form"] = form
        return render(request, "pythonistas-signup.html", context)
Пример #3
0
def profile(request, username):
    from django.core.exceptions import ObjectDoesNotExist
    import cloudinary.uploader as cup
    from core.models import Profile
    print request.user
    print username

    if request.method == 'POST':
        try:
            profile = Profile.objects.get(user=request.user)
        except(ObjectDoesNotExist):
            profile = Profile()
            profile.user = request.user
        profile_picture = request.FILES['profile_photo']
        print profile_picture
        uploaded_image = cup.upload(
            profile_picture,
            crop='limit',
            width=600,
            height=550,
            )
        filename=uploaded_image["secure_url"]
        print filename
        profile.picture = filename
        print profile.picture
        profile.save()
    if request.method == 'GET':
        try:
            profile = Profile.objects.get(user=request.user)
        except(ObjectDoesNotExist):
            return render(request, 'users/profile.html', {"user": request.user, "profile": ""})
    else:
        pass
    return render(request, 'users/profile.html', {"user": request.user, "profile": profile})
Пример #4
0
def register(request):
	"""
	Renders the Chef registration page for installation.
	"""

	# Render the registration page template for a GET request
	if request.method == "GET":
		c = RequestContext(request, {})
		return render_to_response('register.html', context_instance=c)

	# Perform new registration for a POST request
	elif request.method == "POST":
		username = request.POST['username']
		password = request.POST['password']

		# Create a Django super-user first
		chef_superuser = User.objects.create_superuser(username = username,
														password = password, email = "")
		chef_profile = Profile(user = chef_superuser,
								user_type = "ADM")

		chef_profile.save()

		if chef_profile.id:
			print chef_profile.id
			return redirect('/')
Пример #5
0
 def create(self, validated_data):
     """
     Create Profile for user.
     """
     request = self.context.get('request')
     profile = Profile(**validated_data)
     profile.user = request.user
     profile.save()
     return profile
Пример #6
0
 def setUp(self):
     self.profile = Profile(username='******', spent_time=133)
     self.profile.save()
     category1 = Category(name="Категория1",
                          profile=self.profile,
                          spent_time=63)
     category1.save()
     category2 = Category(name="Категория2",
                          profile=self.profile,
                          spent_time=70)
     category2.save()
Пример #7
0
 def setUp(self):
     self.user = User.objects.create_user(username='******',
                                          email="*****@*****.**",
                                          password="******",
                                          first_name="Vinicius",
                                          last_name="Mesel")
     self.profile = Profile(
         user=self.user,
         github="http://www.aaa.com.br",
         linkedin="http://www.aaa.com.br",
         portfolio="http://www.aaa.com.br",
     )
     self.profile.save()
Пример #8
0
def activate(request, uidb64, token):
	try:
		uid = force_text(urlsafe_base64_decode(uidb64))
		user = User.objects.get(pk=uid)
		user_profile = Profile(name=user.username,user=user)
		user_profile.save()
	except(TypeError, ValueError, OverflowError, User.DoesNotExist):
		user = None
	if user is not None and account_activation_token.check_token(user, token):
		user.is_active = True
		user.save()
		messages.info(request, 'infofully verified!')
		return redirect("login")
	else:
		return HttpResponse('Activation link is invalid!')	
Пример #9
0
 def save(self, request):
     user = super(CustomSignupForm, self).save(request)
     account = Account.objects.create(name=user.username)
     profile_model = Profile.get_profile_model(
         self.cleaned_data['account_type'])
     profile_model.objects.create(user=user, account=account)
     return user
Пример #10
0
def save_users(data_users):
    cleaned_users = []
    id_users = {}

    for obj in data_users:
        obj["street"] = obj["address"]["street"]
        obj["city"] = obj["address"]["city"]
        obj["zipcode"] = obj["address"]["zipcode"]

        id_users[obj["id"]] = obj["id"]

        cleaned_users.append(
            Profile(name=obj["name"],
                    email=obj["email"],
                    street=obj["street"],
                    city=obj["city"],
                    zipcode=obj["zipcode"]))

    response_users = Profile.objects.bulk_create(cleaned_users,
                                                 ignore_conflicts=True)
    response_users = remove_unvalid_objects(response_users)

    response_users = Profile.objects.order_by('-pk')[:len(response_users)]
    response_users = list(reversed(response_users))

    id_users = bind_id_with_objects(id_users, response_users)

    return id_users, response_users
Пример #11
0
 def create(self, validated_data):
     """Create a new user with encrypted password and return it"""
     user = get_user_model().objects.create_user(
         **{
             'username': validated_data['username'],
             'email': validated_data['email'],
             'mobile': validated_data['mobile'],
             'password': validated_data['password']
         })
     profile = Profile(
         user=user,
         first_name=validated_data['first_name'],
         last_name=validated_data['last_name'],
         gender=validated_data['gender'],
         dob=validated_data['dob'],
     )
     profile.save()
     return user
Пример #12
0
    def test_model_can_create_a_profile(self):
        """Test the Person model can create a profile."""
        old_count = Profile.objects.count()
        self.user.save()

        self.profile = self.profile = Profile(user=self.user)
        self.profile.save()
        new_count = Profile.objects.count()
        self.assertNotEqual(old_count, new_count)
    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)

        instance.save()
        Group.objects.get(name='workers').user_set.add(instance)
        Profile(user=instance).save()
        return instance
Пример #14
0
 def create(self, validated_data):
     user_data = validated_data.pop('user')
     user = User(**user_data)
     user.set_password(user_data['password'])
     user.save()
     if not Group.objects.filter(name='customer').exists():
         group = Group(name='customer')
         group.save()
     else:
         group = Group.objects.get(name='customer')
     user.groups.add(group)
     user.save()
     profile = Profile(
         user=user,
         last_message=
         '{"date":"null","message":"Bem Vindo","icon":"welcome","title":"Zapidus"}'
     )
     profile.save()
     return profile
Пример #15
0
class CoreTestCase(TransactionTestCase):
    def setUp(self):
        self.profile = Profile(username='******', spent_time=133)
        self.profile.save()
        category1 = Category(name="Категория1",
                             profile=self.profile,
                             spent_time=63)
        category1.save()
        category2 = Category(name="Категория2",
                             profile=self.profile,
                             spent_time=70)
        category2.save()

    def test_get_info(self):
        result = get_profile_data(self.profile)
        self.assertEqual(result['spent_time'], '2h 13m')
        self.assertEqual(result['categories'][0]['name'], 'Категория1')
        self.assertEqual(result['categories'][0]['spent_time'], '1h 3m')
        self.assertEqual(result['categories'][1]['name'], 'Категория2')
        self.assertEqual(result['categories'][1]['spent_time'], '1h 10m')
Пример #16
0
def profile_register(request: HttpRequest) -> HttpResponse:
    if request.method != "POST":
        return redirect("pages_profile_login")

    user_data = {
        'username': request.POST['username'],
        'password': request.POST['password'],
    }

    try:
        user = User(username=user_data['username'])
        user.set_password(user_data['password'])
        user.full_clean()
        user.save()

        Token.objects.create(user=user)

        profile = Profile(user=user)
        profile.full_clean()
        profile.save()

        login(request, user)

        return redirect("pages_profile_list")
    except ValidationError as validation_errors:
        # This errors is a workaround becouse django and jinja2 does not allow
        # a simple thing like "for err in errors['username']" in its template system...
        # shame on you django, shame on you.
        errors = {}

        for key, value in dict(validation_errors).items():
            errors['{}_errors'.format(key)] = value

        return render(request, "profile/signup.html", errors)
Пример #17
0
 def get_context_data(self, **kwargs):
     context = super(PreviewThemeView, self).get_context_data()
     # TODO move this user data to settings.py for a default global Profile
     # and iterate over dict to clean this up
     first_name = self.request.GET.get('first_name') or 'Johnny'
     last_name = self.request.GET.get('last_name') or 'Rotten'
     description = self.request.GET.get('description') or 'I AM TEST'
     short_description = self.request.GET.get(
         'short_description') or 'Developer, Open Source Enthusiast'
     context['user'] = Profile(first_name=first_name,
                               last_name=last_name,
                               description=description,
                               short_description=short_description)
     return context
Пример #18
0
def create_or_update_profile(strategy, backend, uid, response, details, user,  *args, **kwargs):
    if backend.name == 'facebook':
        social = user.social_auth.get(provider='facebook')

        if hasattr(user, 'profile'):
            profile = user.profile
        else:
            profile = Profile(user=user)  # New user

        profile.picture = social.extra_data['picture']['data']['url']
        profile.token = social.extra_data['access_token']
        profile.facebook_user_id = social.extra_data['id']
        profile.save()
Пример #19
0
class ProfileTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='******',
                                             email="*****@*****.**",
                                             password="******",
                                             first_name="Vinicius",
                                             last_name="Mesel")
        self.profile = Profile(
            user=self.user,
            github="http://www.aaa.com.br",
            linkedin="http://www.aaa.com.br",
            portfolio="http://www.aaa.com.br",
        )
        self.profile.save()

    def test_create_profile_with_user(self):
        nome_real = "{} {}".format(self.user.first_name, self.user.last_name)
        self.assertTrue(str(self.profile), nome_real)

    def test_created(self):
        self.assertTrue(Profile.objects.exists())

    def test_created_at(self):
        self.assertIsInstance(self.profile.created_at, datetime)
Пример #20
0
def home(request):
    token = 'EAArs9bPdU9IBALyEhNcpUcTudkZCi9yHkQBH1UCOqLf1LI2AzpN07ZAMYMsKhD6WjmYtZCdJJ9kFzBJxArHotrJbz6NvZClyJvrZABMy81AvBBaYcfbN74UTiZCzDfB1hdGE73Py8tUuFuY1U5aZAMD0B4dFE7Pw7KvRpU3aCNcaQZDZD'
    graph = facebook.GraphAPI(token)
    profile = graph.get_object("me")

    # friends
    friends = graph.get_connections("me", "friends")
    friend_count = int(friends['summary']['total_count'])

    # likes
    likes = graph.get_connections("me", "likes")
    like_count = len(likes['data'])

    # events
    events = graph.get_connections("me", "events")
    event_count = len(events['data'])

    # save to database
    previousProfile = Profile.objects.order_by('-pk')[0]
    currentProfile = Profile(friends=friend_count,
                             likes=like_count,
                             events=event_count)
    currentProfile.save()

    # get changes
    changeInLikes = getattr(previousProfile, 'likes') - getattr(
        currentProfile, 'likes')
    changeInFriends = getattr(previousProfile, 'friends') - getattr(
        currentProfile, 'friends')
    changeInEvents = getattr(previousProfile, 'events') - getattr(
        currentProfile, 'events')

    if changeInLikes == 0:
        trendLikes = 'neutral'
    elif changeInLikes > 0:
        trendLikes = 'positive'
    else:
        trendLikes = 'negative'

    if changeInFriends == 0:
        trendFriends = 'neutral'
    elif changeInFriends > 0:
        trendFriends = 'positive'
    else:
        trendFriends = 'negative'

    if changeInEvents == 0:
        trendEvents = 'neutral'
    elif changeInEvents > 0:
        trendEvents = 'positive'
    else:
        trendEvents = 'negative'

    return render(
        request, 'home.html', {
            'friendCount': friend_count,
            'likeCount': like_count,
            'eventCount': event_count,
            'changeInLikes': abs(changeInLikes),
            'changeInFriends': abs(changeInFriends),
            'changeInEvents': abs(changeInEvents),
            'trendLikes': trendLikes,
            'trendFriends': trendFriends,
            'trendEvents': trendEvents
        })
Пример #21
0
class CustomUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields: list = [
            'fullname',
            'phone',
            'country',
            'level',
            'password',
            'email',
            'role',
            'referral_code',
        ]
        extra_kwargs = {
            "password": {
                "write_only": True,
                'style': {
                    'input_type': 'password'
                }
            },
        }

    def create(self, validated_data):

        # overide create method to hash user password
        password = validated_data.pop("password")
        phone = validated_data.get('phone')
        fullname = validated_data.get('fullname')
        user_role = validated_data.get('role')
        user = CustomUser(**validated_data)
        user.set_password(password)
        user.username = f'{fullname}-{phone}'

        # Check if inputted phone number exists
        referral_code = validated_data.get('referral_code')
        if referral_code is not None:
            if not (referral_qs := Profile.objects.filter(
                    personal_referral_code=referral_code)).exists():
                # if not referral_qs.exists():
                raise serializers.ValidationError("Referral doesn't exists")
        if user_role == "admin":
            user.is_superuser = True
            user.is_staff = True
        user.save()

        # Creates user profile
        user_profile = Profile(user=user)
        user_profile.personal_referral_code = f'https://learnerscorner.org/signup?ref_code={phone}'
        user_profile.save()

        # send verification email to user
        try:
            jwt_token = RefreshToken.for_user(
                user).access_token  # get JWT access token
            current_site_domain = Util.get_host_domain(self.context['request'])
            relative_url = reverse(
                'email_verification_confrim'
            )  # get the relative path to email verification
            absolute_url = f"{current_site_domain}{relative_url}?token={jwt_token}"

            data = {
                'message':
                f"Hi {user.username} use the link below to verify your account \n {absolute_url}",
                'sender': settings.EMAIL_HOST_USER,
                'recipient': user.email,
                'subject': "Email Verification"
            }
            Util.send_email(data)

            return user
        except CustomUser.DoesNotExist:
            return Response({"data": "user with this email does not exists"},
                            status=404)
Пример #22
0
        user_id = int(get_field(old_user, "id"))
        user = User(
            id=user_id,
            username=get_field(old_user, "uname", "") + "_old" + str(user_id),
            first_name=get_field(old_user, "fname", ""),
            last_name=get_field(old_user, "lname", ""),
            email=get_field(old_user, "email", ""),
            is_active=2000 + int(get_field(old_user, "gradyear", -2001)) >
            2018,
        )
        user.save()

        profile = Profile(
            id=user_id,
            user=user,
            biography=get_field(old_user, "bio", ""),
            position=get_field(old_user, "position", ""),
            graduation_year=2000 + int(get_field(old_user, "gradyear", -2001)),
        )
        profile.save()

if ask_reimport("user roles"):
    roles = read_table("user_role")
    writers, _ = Group.objects.get_or_create(name="writers")
    editors, _ = Group.objects.get_or_create(name="editors")
    eics, _ = Group.objects.get_or_create(name="editors-in-chief")
    sponsors, _ = Group.objects.get_or_create(name="sponsors")

    for old_role in roles:
        user_id = int(get_field(old_role, "id"))
        role = int(get_field(old_role, "roleId"))
Пример #23
0
def signup(request):
    name = request.data.get("name")
    surname = request.data.get("surname")
    email = request.data.get("email")
    if email:
        email = email.lower()
    username = request.data.get("username")
    if username:
        username = username.lower()
    error = checkUserAlreadyRegistered(email, username)
    if error:
        return Response({'success': False, 'error': error})
    user = User.objects.create_user(username,
                                    email,
                                    email,
                                    last_login=timezone.now())
    user.first_name = name
    user.last_name = surname
    user.is_active = False
    user.save()
    profile = Profile()
    profile.user = user
    profile.setActivationKey()
    profile.setKeyExpires()
    profile.save()
    createDefaultWallets(profile)

    #set default avatar
    try:
        imageData = getDefaultAvatarImageData()
        ext = settings.DEFAULT_AVATAR_IMAGE_PATH.split('/')[-1].split(".")[-1]
        avatarImageName = "%d.%s" % (profile.user.id, ext)
        data = ContentFile(imageData, name=avatarImageName)
        profile.avatarImage = data
        profile.save()
    except:
        pass

    # Admin Notification
    adminNotification = Notification()
    adminNotification.email = True
    adminNotification.user = User.objects.get(username="******")
    adminNotification.setEmailData(
        "New LWF user registered",
        "notifications/email/admin_email_user_registered.html", {
            'user': user,
        })
    Thread(target=adminNotification.process, args=(), kwargs={}).start()
    sendRegistrationEmail(profile)
    return Response({'success': True})
Пример #24
0
 def CrearPerfil(self):
     print('Creando roles de usuario.')
     profile = Profile(ProfileID=1, ProfileName='Administrador')
     profile.save()
     profile = Profile(ProfileID=2, ProfileName='Consultor')
     profile.save()
     profile = Profile(ProfileID=3, ProfileName='Cliente externo')
     profile.save()
     profile = Profile(ProfileID=4, ProfileName='Cliente interno')
     profile.save()
     profile = Profile(ProfileID=5, ProfileName='Productor')
     profile.save()
     profile = Profile(ProfileID=6, ProfileName='Transportista')
     profile.save()
     return
Пример #25
0
def user_is_shopper(view_cls):
    return Profile.user_is_shopper(view_cls.request.user)
Пример #26
0
    User.objects.all().delete()
    Profile.objects.all().delete()
    users = read_table("user")

    for i, old_user in enumerate(users):
        user_id = int(get_field(old_user, "id"))
        user = User(id=user_id,
                    username=get_field(old_user, "uname", "") + "_old" +
                    str(user_id),
                    first_name=get_field(old_user, "fname", "(no first name)"),
                    last_name=get_field(old_user, "lname", "(no last name)"))
        user.save()

        profile = Profile(
            id=user_id,
            user=user,
            biography=get_field(old_user, "bio", "(no biography)"),
            position=get_field(old_user, "position", "(no position)"),
            graduation_year=2000 + int(get_field(old_user, "gradyear", -2001)))
        profile.save()

if ask_reimport("categories"):
    Section.objects.all().delete()
    categories = read_table("category")

    for old_category in categories:
        parent_id = int(get_field(old_category, "pid"))
        section = Section(id=get_field(old_category, "id"),
                          parent=(Section.objects.get(
                              id=parent_id) if parent_id > 0 else None),
                          name=get_field(old_category, "url_name"),
                          title=get_field(old_category, "name"))
Пример #27
0
def create_profile(sender, **kw):
    u = kw["request"].POST["username"]
    user = User.objects.get(username=u)
    if kw["signal"]:
        profile = Profile(user=user)
        profile.save()