コード例 #1
0
def authorize(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            saved_row = form.save()
            profile = Profile(first_name=form.cleaned_data.get('first_name'),
                              last_name=form.cleaned_data.get('last_name'),
                              email=form.cleaned_data.get('email'),
                              phone=form.cleaned_data.get('phone'),
                              gender=form.cleaned_data.get('gender'),
                              is_veg='N',
                              is_smoke='N',
                              is_alcohol='N',
                              university='Dalhousie',
                              branch='CSE')
            values = profile.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            print(profile.user_id)
            return render_to_response('home.html',
                                      {'profile_user_id': profile.user_id},
                                      locals())
        else:
            return render(request, 'signup.html', {'form': form})
    else:
        form = RegisterForm()
        return render(request, 'signup.html', {'form': form})
コード例 #2
0
ファイル: views.py プロジェクト: y297374507/TaskApp
 def create(self, request, *args, **kwargs):
     nickname = request.data['nickname'] if False else ' '
     sex= request.data['sex'] if False else 1
     phone = request.data['phone'] if False else ' '
     data = {
         'email':request.data['email'],
         'username':request.data['username'],
         'password':request.data['password'],
         'nickname':nickname,
         'sex':sex,
         'phone':phone,
     }
     # 这里还要添加验证模型的东西
     user = User(email = data['email'],username = data['username'],password = data['password'],is_active = 0)
     try:
         user.save()
         profile = Profile(nickname=data['nickname'], sex=data['sex'], phone=data['phone'], user=user,user_id=user.id)
         profile.save()
         signals.user_registered.send(sender=self.__class__, user=user, request=self.request)
         if 1:
             self.send_activation_email(user)
         elif settings.get('SEND_CONFIRMATION_EMAIL'):
             self.send_confirmation_email(user)
         return Response({'status': 'User created success'},
                         status=status.HTTP_201_CREATED)
     except:
         return Response({'status': 'error'},
                         status=status.HTTP_400_BAD_REQUEST)
コード例 #3
0
def overview(request):
    try:
        profile = request.user.get_profile()
    except:
        profile = Profile()
        profile.user = request.user
        profile.save()
    return 'overview.html', {'profile': profile,
                             'groups': profile.get_groups()}
コード例 #4
0
ファイル: replace.py プロジェクト: 0x55AAh/anthill_gaming
 def replace(profile: Profile, target: str, replaces: Dict[Any, Any]) -> None:
     """Apply all replace operations on profile payload."""
     matches = profile.find_payload(target, lambda x: x.value in replaces)
     for match in matches:
         new_value = replaces[match.value]
         # do replace operation without committing to database
         profile.update_payload(match.full_path, new_value, commit=False)
     if matches:
         # finally commit changes to database
         profile.save()
コード例 #5
0
    async def prepare_db_request(self, data: dict) -> dict:
        """
        Prepare request to db. Replace Profile.user_id to int32 value from db.
        Args:
            data: dict with user data for Profile object.

        Returns:  dict with user profile.

        """
        profile = Profile(**data)
        profile.user_id = await get_next_sequence_value(
            self.request.app['db'], "user_id")
        return profile.to_dict()
コード例 #6
0
 def calculate_over_40(self):
     from profile.models import Profile
     try:
         ## try to get the user's DOB from their profile, if no profile
         # is made, assume they are over 40
         dob = Profile.get_for_user(self.user).dob
     except AttributeError, Profile.DoesNotExist:
         dob = datetime.date(1915, 7, 21)
コード例 #7
0
ファイル: views.py プロジェクト: apalade/fingo
def _check_and_save_user_atomic(fb_user):
  try:
    #FIXME: This can be improved to be checked after uid in the facebook cookie
    user = User.objects.get(email=fb_user['email'])
    return (user, None, False)

  except User.DoesNotExist:
    # Save it to our db
    username = _get_username_from_fb_user(fb_user)
    user = User.objects.create(username=username, email=fb_user['email'],
          first_name=fb_user['first_name'].title(),
          last_name = fb_user['last_name'].title())
    profile = Profile()
    profile.user = user
    profile.save(force_insert=True)
    
    return (user, profile, True)
コード例 #8
0
ファイル: FAA.py プロジェクト: bovine/flightloggin2
 def calculate_over_40(self):
     from profile.models import Profile
     try:
         ## try to get the user's DOB from their profile, if no profile
         # is made, assume they are over 40
         dob = Profile.get_for_user(self.user).dob
     except AttributeError, Profile.DoesNotExist:
         dob = datetime.date(1915,7,21)
コード例 #9
0
ファイル: views.py プロジェクト: traciarms/mySocial
def create_user(request):
    if request.method == "POST":
        form = ProfileCreationForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            if request.user.is_authenticated():
                user = request.user
                user.backend = "django.contrib.auth.backends.ModelBackend"
            else:
                user = form.save()
            profile = Profile()
            profile.user = user
            user.email = data["email"]
            profile.dob = data["dob"]
            profile.gender = data["gender"]
            profile.phone = data["phone"]
            profile.save()
            user.save()
            user = authenticate(username=request.POST["username"], password=request.POST["password1"])
            login(request, user)

            return HttpResponseRedirect(reverse("home"))
    else:
        if request.user:
            user = request.user
            context = {}
            context["username"] = user.username
            context["first_name"] = user.first_name
            context["last_name"] = user.last_name
            context["email"] = user.email

        form = ProfileCreationForm(context)

    return render(request, "profile_registration.html", {"form": form})
コード例 #10
0
def new_user(sender, instance, **kwargs):
    if not Profile.objects.filter(user=instance).count():
        profile = Profile(user=instance)
        profile.save()
    else:
        profile = Profile.objects.get(user=instance)

    avatars = os.path.join(_settings.AVATARS_DIR, profile.slug)
    if not os.path.exists(avatars):
        os.makedirs(avatars)

    # FIXME:
    # FIXME: Lanzar señal que atrape la app core y cree sus directorios.
    wallpapers = os.path.join(django_settings.UPLOAD_DIR, profile.slug)
    if not os.path.exists(wallpapers):
        os.makedirs(wallpapers)

    return True
コード例 #11
0
ファイル: views.py プロジェクト: dimoniet/flightloggin2
def bargraph_image(request, column, func, agg):

    import bargraph as g

    if agg == "person":
        Graph = g.PersonBarGraph

    elif agg == "student":
        Graph = g.StudentBarGraph

    elif agg == "captain":
        Graph = g.CaptainBarGraph

    elif agg == "first_officer":
        Graph = g.FOBarGraph

    elif agg == "instructor":
        Graph = g.InstructorBarGraph

    elif agg == "type":
        Graph = g.PlaneTypeBarGraph

    elif agg == "tailnumber":
        Graph = g.TailnumberBarGraph

    elif agg == "manufacturer":
        Graph = g.ManufacturerBarGraph

    elif agg == "category_class":
        Graph = g.CatClassBarGraph

    elif agg == "model":
        Graph = g.ModelBarGraph

    elif agg == "year":
        Graph = g.YearBarGraph

    elif agg == "month":
        Graph = g.MonthBarGraph

    elif agg == "day_of_the_week":
        Graph = g.DOWBarGraph

    elif agg == "month_year":
        Graph = g.MonthYearBarGraph

    else:
        assert False, "Agg not added to generator view"

    graph = Graph(request.display_user, column, agg, func)

    from profile.models import Profile

    graph.color_profile = Profile.get_for_user(request.display_user).style

    return graph.as_png()
コード例 #12
0
    def create(self, validated_data):
        """
        Create and return a new User instance, given the validated data.
        """

        profile_data = validated_data.pop('profile')

        user = super(UserSerializer, self).create(validated_data)
        user.date_joined = datetime.today()
        user.set_password(validated_data['password'])
        user.save()

        profile = Profile(
            user=user,
            cba_username=profile_data.get('cba_username').strip(),
            cba_user_token=profile_data.get('cba_user_token').strip())
        profile.save()

        return user
コード例 #13
0
ファイル: forms.py プロジェクト: fpSpindola/Villagescc_new_ui
 def save(self, location, language):
     data = self.cleaned_data
     user = super(RegistrationForm, self).save(commit=False)
     user.last_login = timezone.now()
     user.email = data['email']
     user.first_name = data['first_name']
     # user.last_name = data['last_name']
     user.save()
     profile = Profile(user=user, name=data.get('name', data['username']))
     if not location.id:
         location.save()
     profile.location = location
     # profile.name = data['first_name'] + ' ' + data['last_name']
     profile.save()
     profile.settings.email = data['email']
     profile.settings.language = language
     profile.settings.feed_radius = -1
     profile.settings.save()
     return profile
コード例 #14
0
def create_profile():
    data = request.get_json()
    new_profile = Profile(name=data['name'],
                          address=data['address'],
                          phone_number=data['phone_number'])

    db.session.add(new_profile)
    db.session.commit()

    return jsonify({'message': 'New profile created!'})
コード例 #15
0
ファイル: views.py プロジェクト: mdek/flightloggin2
def bargraph_image(request, column, func, agg):

    import bargraph as g

    if agg == 'person':
        Graph = g.PersonBarGraph

    elif agg == 'student':
        Graph = g.StudentBarGraph

    elif agg == 'captain':
        Graph = g.CaptainBarGraph

    elif agg == 'first_officer':
        Graph = g.FOBarGraph

    elif agg == 'instructor':
        Graph = g.InstructorBarGraph

    elif agg == 'type':
        Graph = g.PlaneTypeBarGraph

    elif agg == 'tailnumber':
        Graph = g.TailnumberBarGraph

    elif agg == 'manufacturer':
        Graph = g.ManufacturerBarGraph

    elif agg == 'category_class':
        Graph = g.CatClassBarGraph

    elif agg == 'model':
        Graph = g.ModelBarGraph

    elif agg == 'year':
        Graph = g.YearBarGraph

    elif agg == 'month':
        Graph = g.MonthBarGraph

    elif agg == 'day_of_the_week':
        Graph = g.DOWBarGraph

    elif agg == 'month_year':
        Graph = g.MonthYearBarGraph

    else:
        assert False, "Agg not added to generator view"

    graph = Graph(request.display_user, column, agg, func)

    from profile.models import Profile
    graph.color_profile = Profile.get_for_user(request.display_user).style

    return graph.as_png()
コード例 #16
0
def create_profile_data(strategy,
                        user,
                        response,
                        details,
                        is_new=False,
                        *args,
                        **kwargs):
    if is_new:
        if 'fullname' in details:
            full_name = details['fullname']
        else:
            full_name = user.username
        new_profile = Profile(user=user, name=full_name)
        new_profile.user_id = user.id
        new_profile.name = user.username
        new_profile.user.email = details[
            'email'] if 'email' in details else None

        url = 'https://graph.facebook.com/{0}/picture'.format(response['id'])
        try:
            img_content = request('GET', url, params={'type': 'large'})
            file_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
                'uploads', 'facebook', '{0}__social.jpg'.format(user.id))
            with open(file_path, 'wb+') as destination:
                img_file = ContentFile(img_content.content)
                for chunk in img_file.chunks():
                    destination.write(chunk)
            new_profile.photo = 'facebook/{0}__social.jpg'.format(user.id)
            new_profile.save()

            profile_settings = Settings.objects.get(profile_id=new_profile.id)
            profile_settings.email = details[
                'email'] if 'email' in details else None
            profile_settings.feed_radius = -1
            profile_settings.save()
            return
        except Exception as e:
            raise e
    elif user.date_joined >= (datetime.datetime.now(tz=pytz.utc) -
                              datetime.timedelta(hours=1)):
        existing_profile = Profile.objects.get(user_id=user.id)
        url = 'https://graph.facebook.com/{0}/picture'.format(response['id'])
        try:
            img_content = request('GET', url, params={'type': 'large'})
            file_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
                'uploads', 'facebook', '{0}__social.jpg'.format(user.id))
            with open(file_path, 'wb+') as destination:
                img_file = ContentFile(img_content.content)
                for chunk in img_file.chunks():
                    destination.write(chunk)
            existing_profile.photo = 'facebook/{0}__social.jpg'.format(user.id)
            existing_profile.save()
        except Exception as e:
            raise e
コード例 #17
0
ファイル: models.py プロジェクト: joelbrady/unswfingr
def create_fingr_user(email, password, **kwargs):
    """
    This function takes clean data to create a fingr user,
    please do not create one yourself
    """

    # the django create_user method automatically saves it in the database for us
    django_user = User.objects.create_user(username=email, email=email, password=password)

    initial_location = UserLocation(latitude=UNSW_LATITUDE, longitude=UNSW_LONGITUDE)
    initial_location.save()

    profile = Profile()
    profile.save()

    fingr_user = FingrUser(
        django_user=django_user, username=email, email=email, my_location=initial_location, profile=profile, **kwargs
    )
    fingr_user.save()

    return fingr_user
コード例 #18
0
    async def post(self) -> Union[web.json_response, web.HTTPException]:
        """
        Take user credentials and check if user exist.
        If exist - return his profile in JSON. Else -> HTTPException
        Returns: User profile or Exception

        """
        request_data = await self.request.json()

        result = await self.find_user(request_data)

        if not result:
            raise web.HTTPNotFound(text="User not found")

        profile = Profile(**clean_data(result))

        if profile.check_password(request_data['password']):
            await profile.fetch_contacts(self.request.app['db'])

            return web.json_response(profile.to_dict(), status=200)

        raise web.HTTPNotAcceptable(text="Wrong password")
コード例 #19
0
ファイル: views.py プロジェクト: dratkov/easy_mon
def complete_registration(request):
        if request.user.is_authenticated():
            return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
        try:
            identity_id = request.session.get('users_complete_reg_id', None)
            user_map = models.UserMap.objects.get(identity__id=identity_id)
        except models.UserMap.DoesNotExist:
            return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
        if not user_map.user.username:
            user_map.user.username = user_map.user.email.split('@')[0]
        user_map.user.save()
        profile = Profile(user=user_map.user, summa=0)
        profile.save()
        user_map.verified = True
        user_map.save()

        user = auth.authenticate(user_map=user_map)
        auth.login(request, user)

        messages.info(request, u'Добро пожаловать!')
        del request.session['users_complete_reg_id']
        return redirect('/')
コード例 #20
0
def complete_registration(request):
    if request.user.is_authenticated():
        return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
    try:
        identity_id = request.session.get('users_complete_reg_id', None)
        user_map = models.UserMap.objects.get(identity__id=identity_id)
    except models.UserMap.DoesNotExist:
        return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
    if not user_map.user.username:
        user_map.user.username = user_map.user.email.split('@')[0]
    user_map.user.save()
    profile = Profile(user=user_map.user, summa=0)
    profile.save()
    user_map.verified = True
    user_map.save()

    user = auth.authenticate(user_map=user_map)
    auth.login(request, user)

    messages.info(request, u'Добро пожаловать!')
    del request.session['users_complete_reg_id']
    return redirect('/')
コード例 #21
0
    def insert_mock_data(self):
        import csv
        from profile.models import Profile
        from audioanalysis.models import Audio
        from django.db import connection
        # from django.contrib.auth.models import User
        from profile import definitions
        import random
        import pycountry
        from faker import Faker
        from datetime import datetime
        from users.models import CustomUser as User



        #self.delete_all_users_except_admins()

        fake = Faker(['en_US']) 

        for i in range(0, 1000):
            first_name = fake.first_name()
            last_name = fake.last_name()
            
            # get first character of first name, full last name, 4 random numbers
            nums = ''.join([str(random.randint(0,9)) for p in range(0,4)])
            email = first_name[0][:1].lower()+last_name+nums+random.choice(self.email_prefix)

            # 1994-12-21
            birth_date = fake.date_of_birth(tzinfo=None, minimum_age=0, maximum_age=115).strftime('%Y-%m-%d')
            country = random.choice(list(pycountry.countries)).name
            # Create a user that will go in auth_user table
            user_one_to_one = self.create_random_user(email_from_profile_object=email)
            profile = Profile(user=user_one_to_one, first_name=first_name, last_name=last_name, email=email, birth_date=birth_date, country=country)
            #print(profile)
            profile.save()
            # connect audio file to user 
            audio_file = Audio(user=user_one_to_one, name=self.s3_urls[0].split("/")[-1], s3_url=self.s3_urls[0])
            audio_file.save()
            audio_file = Audio(user=user_one_to_one, name=self.s3_urls[1].split("/")[-1], s3_url=self.s3_urls[1])
            audio_file.save()

            print("Created user " + str(i))
        
        # Create admin users
        
        user = User.objects.create_superuser('lmp004', '*****@*****.**', 'password')
        profile = Profile(user=user, first_name='Logan', last_name="Phillips", email='*****@*****.**', birth_date='1996-04-24', country='America')
        # profile = Profile(user=user, first_name='Logan', last_name=None, email='*****@*****.**', birth_date=None, country=None)
        profile.save()
コード例 #22
0
ファイル: forms.py プロジェクト: grahamking/goodenergy
    def save_and_login(self, request):
        'Create this user in the database, log that user in, and return the Profile'
        
        first_name = self.cleaned_data['first_name']
        last_name = self.cleaned_data['last_name']

        #username = defaultfilters.slugify(self.cleaned_data['email'])[:30]
        username = Profile.objects.unique_username(first_name, last_name)
        email = self.cleaned_data['email']
        password = self.cleaned_data['password']

        new_user = User.objects.create_user(username, email, password)
        new_user.first_name = first_name
        new_user.last_name = last_name
        new_user.save()

        geuser = Profile(user = new_user, timezone=self.cleaned_data['timezone'])

        referer = None
        referer_id = None
        if 'f' in request.GET:
            referer_id = request.GET['f']
        elif 'f' in request.COOKIES:
            referer_id = request.COOKIES['f']
        if referer_id:
            try:
                referer = Profile.objects.get(pk = long(referer_id))
                referer.add_participation_points(points=5)
                referer.save()

                geuser.referer = referer
            except (Profile.DoesNotExist, ValueError):
                pass
        geuser.save()

        if self.cleaned_data['picture']:
            relative_pic_name = save_picture(geuser, self.cleaned_data['picture'])
            geuser.avatar = relative_pic_name
        #else:
        #    relative_pic_name = save_gravatar(geuser)

        geuser.save()
        
        if self.cleaned_data['group']:
            group_id = self.cleaned_data['group']
            group = Group.objects.get(pk = group_id)
            geuser.groups.add(group)

        user = authenticate(username=new_user.username, password=password)
        login(request, user)

        return geuser
コード例 #23
0
def proper_ad(request):
    u = getattr(request, "display_user", None) or request.user
    style = Profile.get_for_user(u).style
    
    if True: #random.choice([True] * 20 + [False]):
        ad_text = GOOGLE_ADS[style]
    else:
        ad_text = WIKI_ADS[style]
    
    #######
    
    import os
    CSS_URL = os.path.join(settings.MEDIA_URL, "css", "style-%s" % style)
    
    return {"proper_ad": ad_text, 'CSS_URL': CSS_URL}
コード例 #24
0
def proper_ad(request):
    u = getattr(request, "display_user", None) or request.user
    style = Profile.get_for_user(u).style

    if True:  #random.choice([True] * 20 + [False]):
        ad_text = GOOGLE_ADS[style]
    else:
        ad_text = WIKI_ADS[style]

    #######

    import os
    CSS_URL = os.path.join(settings.MEDIA_URL, "css", "style-%s" % style)

    return {"proper_ad": ad_text, 'CSS_URL': CSS_URL}
コード例 #25
0
def users_search(request, key):
    blocked_users = set()
    for e in request.user.profile.blocking.filter(
            user_id=request.user.profile).select_related('blocking_user_id'):
        blocked_users.add(e.blocking_user_id)
    try:
        users = Profile.filter(username__icontains=key).exclude(blocked_users)
    except Profile.DoesNotExist:
        users = None

    context = {
        'title': 'Search | ClickTime',
        'users': users,
    }
    return render(request, 'home/users_search.html', context=context)
コード例 #26
0
def css_path(request):
    """ Return the path to the CSS directory based on the display user's
        profile. if no display user, it falls back to request.user
    """
    
    return {}
    
    u = getattr(request, "display_user", None) or request.user

    from profile.models import Profile
    style = Profile.get_for_user(u).style
    
    import os
    CSS_URL = os.path.join(settings.MEDIA_URL, "css", "style-%s" % style)
         
    return {"CSS_URL": CSS_URL}
コード例 #27
0
ファイル: sync_users.py プロジェクト: Jafte/intranet
    def sync_users(self, xml, company):
        for person in xml.findall('person'):
            email = person.find('email-address').text
            first_name = person.find('first-name').text
            last_name = person.find('last-name').text
            basecamp_id = person.find('id').text
            created = False
            try:
                user = User.objects.get(profile__basecamp_id=basecamp_id)
                user.email = email
                self.stdout.write("User %s already exist." % user)
            except User.DoesNotExist:
                try:
                    user = User.objects.get(email=email)
                    created = True
                    self.stdout.write("User %s already exist." % user)
                except User.DoesNotExist:
                    username = email.split('@')[0]
                    try:
                        User.objects.get(username__iexact=username)
                        while True:
                            username = sha_constructor(str(random.random()).encode('utf-8')).hexdigest()[:5]
                            try:
                                User.objects.get(username__iexact=username)
                            except User.DoesNotExist:
                                break
                    except User.DoesNotExist:
                        pass

                    user = UserenaSignup.objects.create_user(username,
                                             email,
                                             username+username,
                                             not userena_settings.USERENA_ACTIVATION_REQUIRED,
                                             userena_settings.USERENA_ACTIVATION_REQUIRED)
                    created = True
                    self.stdout.write("User %s creates." % user)

            if first_name:
                user.first_name = first_name
            if last_name:
                user.last_name = last_name
            user.save()

            company.add_user(user)

            try:
                account = Profile.objects.get(user=user)
            except Profile.DoesNotExist:
                account = Profile(user=user)
                account.save()

            if created:
                account.basecamp_id = basecamp_id
                account.save()
コード例 #28
0
def edit(request):
    try:
        profile = request.user.get_profile()
    except Profile.DoesNotExist:
        profile = Profile(user=request.user)
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(edit) + '?saved')
    else:
        form = ProfileForm(instance=profile)

    return render_to_response('profile/edit.html',
                              {'form': form,
                               'saved': True if 'saved' in request.GET\
                                   else False},
                              context_instance = RequestContext(request))
コード例 #29
0
ファイル: models.py プロジェクト: Prachich20/bbl
    def create_players(self, team,  name, coach, height, score=score):
        team_name = Team.objects.filter(name=team).first()
        player = Players.objects.filter(name=name, team=team_name).first()
        if not player:
            player = Players()

        player.team = team_name
        player.name = name
        player.score = score
        player.coach = coach
        player.height = height
        if coach is True:
            coach_exists = Players.objects.filter(team=team_name, is_coach=True).first()
            if coach_exists is not None:
                raise ValueError("Cannot have more than 1 coach in a team.")
            else:
                player.is_coach = coach
        player.save()
        Profile().add_user(player=player)
コード例 #30
0
ファイル: decorator.py プロジェクト: bovine/flightloggin2
    def determine(self, view, field, request, *args, **kwargs):
        
        if not getattr(request, 'shared'):
            ## if it's not shared, then do nothing (user is viewing their
            ## own account)
            return view(request, *args, **kwargs)
        
        user = request.display_user
        
        from profile.models import Profile
        profile = Profile.get_for_user(user)
        
        if not field == 'NEVER':
            from django.conf import settings
            if getattr(user, "id", 0) == settings.DEMO_USER_ID:
                ## demo user, let them go hog wild
                return view(request, *args, **kwargs)
                
            go_ahead = getattr(profile, "%s_share" % field)

        
        ## can not view page because the user doesn't want it shared,
        ## either redirect to a page that can be shared, or redirect
        ## to the root page
        if field == 'NEVER' or not go_ahead:
            from django.http import HttpResponseRedirect
            from django.core.urlresolvers import reverse
            
            if getattr(profile, "logbook_share"):
                url = reverse('logbook', kwargs={"username": user.username})
            elif getattr(profile, "other_share"):
                url = reverse('linegraphs', kwargs={"username": user.username})
            else:
                url = "/"
                
            return HttpResponseRedirect(url)
        
        # passes validation, render the view    
        return view(request, *args, **kwargs) 
コード例 #31
0
ファイル: decorator.py プロジェクト: mdek/flightloggin2
    def determine(self, view, field, request, *args, **kwargs):

        if not getattr(request, 'shared'):
            ## if it's not shared, then do nothing (user is viewing their
            ## own account)
            return view(request, *args, **kwargs)

        user = request.display_user

        from profile.models import Profile
        profile = Profile.get_for_user(user)

        if not field == 'NEVER':
            from django.conf import settings
            if getattr(user, "id", 0) == settings.DEMO_USER_ID:
                ## demo user, let them go hog wild
                return view(request, *args, **kwargs)

            go_ahead = getattr(profile, "%s_share" % field)

        ## can not view page because the user doesn't want it shared,
        ## either redirect to a page that can be shared, or redirect
        ## to the root page
        if field == 'NEVER' or not go_ahead:
            from django.http import HttpResponseRedirect
            from django.core.urlresolvers import reverse

            if getattr(profile, "logbook_share"):
                url = reverse('logbook', kwargs={"username": user.username})
            elif getattr(profile, "other_share"):
                url = reverse('linegraphs', kwargs={"username": user.username})
            else:
                url = "/"

            return HttpResponseRedirect(url)

        # passes validation, render the view
        return view(request, *args, **kwargs)
コード例 #32
0
ファイル: views.py プロジェクト: mdek/flightloggin2
def fb_registration_callback(request):
    """
    This view only gets hit by the facebook callback when a user registers.
    """
    signed_request = request.POST['signed_request']
    response = parse_signed_request(signed_request, settings.FACEBOOK_SECRET)
    data = response['registration']

    u = User(
        username=data['username'],
        email=data['email'],
        first_name=data['first_name'],
        last_name=data['last_name'],
    )

    d, m, y = data['birthday'].split('/')
    dob = datetime.datetime(year=y, month=m, date=d)

    p = Profile(
        user=u,
        dob=dob,
    )

    print response
コード例 #33
0
ファイル: views.py プロジェクト: dratkov/easy_mon
def login_on_activation(sender, user, request, **kwargs):
    profile = Profile(user=user, summa=0)
    profile.save()
    user.backend='django.contrib.auth.backends.ModelBackend'
    login(request,user)
コード例 #34
0
def login_on_activation(sender, user, request, **kwargs):
    profile = Profile(user=user, summa=0)
    profile.save()
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)
コード例 #35
0
ファイル: views.py プロジェクト: Jackstone92/newsmarkr
def edit_about(userId):
    """ Profile post method to edit about """
    edit_about_form = EditAbout()

    if edit_about_form.validate_on_submit():
        birthday = edit_about_form.birthday.data
        political_spectrum = edit_about_form.political_spectrum.data
        political_party = edit_about_form.political_party.data
        favourite_news_websites = edit_about_form.favourite_news_websites.data
        allow_location_detection = edit_about_form.allow_location_detection.data

        profile = Profile.query.filter_by(user_id=userId).first()
        if profile:
            # update profile
            if profile.birthday != birthday:
                profile.birthday = birthday
                db.session.flush()

            if profile.political_spectrum != political_spectrum:
                profile.political_spectrum = political_spectrum
                db.session.flush()

            if profile.political_party != political_party:
                profile.political_party = political_party
                db.session.flush()

            if profile.favourite_news_websites != ",".join(
                    favourite_news_websites):
                profile.favourite_news_websites = ",".join(
                    favourite_news_websites)
                db.session.flush()

            if profile.allow_location_detection == True and allow_location_detection == 'no' or profile.allow_location_detection == False and allow_location_detection == 'yes':
                if allow_location_detection == 'yes':
                    profile.allow_location_detection = True
                else:
                    profile.allow_location_detection = False

                db.session.flush()
        else:
            # create new profile
            # convert allow_location_detection to bool
            allow_bool = None
            if allow_location_detection == 'yes':
                allow_bool = True
            else:
                allow_bool = False

            profile = Profile(userId, birthday, political_spectrum,
                              political_party, favourite_news_websites,
                              allow_bool, None, None, None)
            db.session.add(profile)
            db.session.flush()

        # if allow_location_detection, get location
        if profile.allow_location_detection == True:
            g = geocoder.ip('me')
            if profile.location != g.city + ", " + g.country or profile.lat != g.latlng[
                    0] or profile.lon != g.latlng[1]:
                # add location
                profile.lat = g.latlng[0]
                profile.lon = g.latlng[1]
                profile.location = g.city + ", " + g.country
                db.session.flush()

        db.session.commit()

    return redirect(url_for('about'))
コード例 #36
0
ファイル: main.py プロジェクト: vchernetsov/test-flask
def before_request():
    # Begin transaction
    g.db = SQLA_session()
    g.user = profile_model.query_db().get(session["user_id"])