示例#1
0
    def index(request):
        all_achievements = Achievement.objects.filter(name="Hello World")
        all_goals = Goal.objects.all()
        completed_goals = Goal.done(True)
        open_goals = Goal.done(False)
        # return render(request, 'templates/homeScreen.html')
        return HttpResponse(f"# of Achievements: <br># of Goals: {all_achievements}<br> # of goals: {len(all_goals)} # of completed goals: {len(completed_goals)}. # of open goals{len(open_goals)}")




# def vote(request, goal_id):
#     goal = get_object_or_404(Question, pk=question_id)
#     try:
#         selected_choice = question.choice_set.get(pk=request.POST['choice'])
#     except (KeyError, Choice.DoesNotExist):
#         # Redisplay the question voting form.
#         return render(request, 'polls/detail.html', {
#             'question': question,
#             'error_message': "You didn't select a choice.",
#         })
#     else:
#         selected_choice.votes += 1
#         selected_choice.save()
#         # Always return an HttpResponseRedirect after successfully dealing
#         # with POST data. This prevents data from being posted twice if a
#         # user hits the Back button.
#         return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
示例#2
0
 def archive(self, request, pk=None, **kwargs):
     """
     Override this method as we don't want to actually delete the goal,
     just disable it.
     :param instance: The goal to disable
     :return: None
     """
     goal = self.get_object()
     # If I'm an advisor or the goal is unsupervised,
     # archive the goal immediately.
     sr = SupportRequest.get_current(request, as_obj=True)
     # check helped user instead if support request is active
     user, sr_id = (sr.user, sr.id) if sr else (request.user, None)
     if not goal.account.supervised or user.is_advisor:
         check_state(Goal.State(goal.state), [
             Goal.State.ACTIVE, Goal.State.ARCHIVE_REQUESTED,
             Goal.State.INACTIVE
         ])
         Event.ARCHIVE_GOAL.log('{} {}'.format(request.method,
                                               request.path),
                                user=request.user,
                                obj=goal,
                                support_request_id=sr_id)
         # Set the state to archive requested,
         # as the call to archive() requires it.
         goal.state = Goal.State.ARCHIVE_REQUESTED.value
         goal.archive()
     else:
         # I'm a client with a supervised goal, just change the status to
         # ARCHIVE_REQUESTED, and add a notification
         check_state(Goal.State(goal.state),
                     [Goal.State.ACTIVE, Goal.State.INACTIVE])
         Event.ARCHIVE_GOAL_REQUESTED.log('{} {}'.format(
             request.method, request.path),
                                          user=request.user,
                                          obj=goal,
                                          support_request_id=sr_id)
         # Flag the goal as archive requested.
         goal.state = Goal.State.ARCHIVE_REQUESTED.value
         # TODO: Add a notification to the advisor that the goal is archive requested.
         goal.save()
     return Response(serializers.GoalSerializer(goal).data)
示例#3
0
    def get_context_data(self, *args, **kwargs):
        goal_pk = kwargs.get("goal_pk", None)
        ctx = super(PortfolioAssetClasses, self).get_context_data(*args, **kwargs)

        if goal_pk:
            goal = get_object_or_404(Goal, pk=goal_pk)
            ctx["portfolio_set"] = goal.portfolio_set
        else:
            ctx["portfolio_set"] = Goal().portfolio_set

        return ctx
示例#4
0
    def calculate_all_portfolios(self, request, pk=None, **kwargs):
        """
        Called to calculate all the portfolio objects for 100 different risk scores for the supplied settings.
        """
        goal = self.get_object()

        check_state(Goal.State(goal.state), Goal.State.ACTIVE)

        setting_str = request.query_params.get('setting', None)
        if not setting_str:
            logger.debug(
                'setting parameter missing from calculate_all_portfolios query'
            )
            raise ValidationError(
                "Query parameter 'setting' must be specified and a valid JSON string"
            )
        try:
            setting = ujson.loads(setting_str)
        except ValueError:
            logger.debug(
                'setting parameter for calculate_all_portfolios query not valid json'
            )
            raise ValidationError(
                "Query parameter 'setting' must be a valid json string")

        # Create the settings from the dict
        serializer = serializers.GoalSettingStatelessSerializer(data=setting)
        serializer.is_valid(raise_exception=True)
        settings = serializer.create_stateless(serializer.validated_data, goal)

        # Calculate the portfolio
        try:
            data_provider = DataProviderDjango()
            execution_provider = ExecutionProviderDjango()
            data = [
                self.build_portfolio_data(item[1], item[0]) for item in
                calculate_portfolios(settings=settings,
                                     data_provider=data_provider,
                                     execution_provider=execution_provider)
            ]
            return Response(data)
        except Unsatisfiable as e:
            rdata = {'reason': "No portfolio could be found: {}".format(e)}

            if e.req_funds is not None:
                rdata['req_funds'] = e.req_funds

            return Response({'error': rdata},
                            status=status.HTTP_400_BAD_REQUEST)
示例#5
0
    def get(self, request, *args, **kwargs):
        portfolio_set = Goal().portfolio_set
        goal_pk = kwargs.get("goal_pk", None)
        if goal_pk:
            try:
                goal = Goal.objects.get(pk=goal_pk,
                                        account__primary_owner=self.client)
            except ObjectDoesNotExist:
                goal = None

            if goal:
                if goal.is_custom_size:
                    if goal.portfolios in [None, "{}", "[]", ""]:
                        try:
                            portfolios = calculate_portfolios(goal)
                            goal.portfolios = ujson.dumps(portfolios, double_precision=2)
                            goal.save()
                        except OptimizationException:
                            goal.custom_regions = None
                            goal.save()
                            portfolios = ujson.loads(goal.portfolio_set.portfolios)
                    else:
                        portfolios = ujson.loads(goal.portfolios)
                else:
                    portfolios = ujson.loads(goal.portfolio_set.portfolios)

                ret = []
                for k in portfolios:
                    new_pr = {
                        "risk": int(100 * portfolios[k]["risk"]) / 100,
                        "expectedReturn": portfolios[k]["expectedReturn"],
                        "volatility": portfolios[k]["volatility"],
                        'allocations': portfolios[k]["allocations"]
                    }
                    ret.append(new_pr)
                return HttpResponse(ujson.dumps(ret), content_type="application/json")

        ret = []
        portfolios = ujson.loads(portfolio_set.portfolios)
        for k in portfolios:
            new_pr = {
                "risk": int(100 * portfolios[k]["risk"]) / 100,
                "expectedReturn": portfolios[k]["expectedReturn"],
                "volatility": portfolios[k]["volatility"],
                'allocations': portfolios[k]["allocations"]
            }
            ret.append(new_pr)

        return HttpResponse(ujson.dumps(ret), content_type="application/json")
示例#6
0
    def revert_selected(self, request, pk=None, **kwargs):
        """
        Called to revert the current selected-settings to the approved-settings
        Returns a validation error if there is no approved-settings.
        """
        goal = self.get_object()
        check_state(Goal.State(goal.state), Goal.State.ACTIVE)
        if not goal.approved_settings:
            raise ValidationError("No settings have yet been approved for "
                                  "this Goal, cannot revert to last approved.")
        sr_id = SupportRequest.get_current(request)
        Event.REVERT_SELECTED_SETTINGS.log('{} {}'.format(
            request.method, request.path),
                                           user=request.user,
                                           obj=goal,
                                           support_request_id=sr_id)
        goal.revert_selected()
        serializer = serializers.GoalSettingSerializer(goal.selected_settings)

        return Response(serializer.data)
def calculate_portfolios():
    # calculate default portfolio
    yahoo_api = get_api("YAHOO")

    for ps in PortfolioSet.objects.all():
        goal = Goal()
        goal.custom_portfolio_set = ps
        ps.portfolios = json.dumps(calculate_portfolios_for_goal(goal, api=yahoo_api))
        ps.save()

    # calculate portfolios
    for goal in Goal.objects.all():
        if goal.is_custom_size:
            goal.portfolios = json.dumps(calculate_portfolios_for_goal(goal, api=yahoo_api))
            goal.save()
示例#8
0
    def calculate_portfolio(self, request, pk=None, **kwargs):
        """
        Called to calculate a portfolio object for a set of supplied settings.
        """
        goal = self.get_object()

        check_state(Goal.State(goal.state),
                    [Goal.State.ACTIVE, Goal.State.INACTIVE])

        setting_str = request.query_params.get('setting', None)
        if not setting_str:
            raise ValidationError(
                "Query parameter 'setting' must be specified and a valid JSON string"
            )
        try:
            setting = ujson.loads(setting_str)
        except ValueError:
            raise ValidationError(
                "Query parameter 'setting' must be a valid json string")

        # Create the settings object from the dict
        serializer = serializers.GoalSettingStatelessSerializer(data=setting)
        serializer.is_valid(raise_exception=True)
        settings = serializer.create_stateless(serializer.validated_data, goal)

        try:
            data = self.build_portfolio_data(
                calculate_portfolio(
                    settings=settings,
                    data_provider=DataProviderDjango(),
                    execution_provider=ExecutionProviderDjango()))
            return Response(data)
        except Unsatisfiable as e:
            rdata = {'reason': "No portfolio could be found: {}".format(e)}
            if e.req_funds is not None:
                rdata['req_funds'] = e.req_funds

            return Response({'error': rdata},
                            status=status.HTTP_400_BAD_REQUEST)
示例#9
0
    def approve_selected(self, request, pk=None, **kwargs):
        """
        Called to make the currently selected settings approved by the advisor,
        ready to be activated next time the account is processed (rebalance).
        """
        sr = SupportRequest.get_current(request, as_obj=True)
        # check helped user instead if support request is active
        user, sr_id = (sr.user, sr.id) if sr else (request.user, None)
        if not user.is_advisor:
            raise PermissionDenied('Only an advisor can approve selections.')

        goal = self.get_object()
        check_state(Goal.State(goal.state),
                    [Goal.State.ACTIVE, Goal.State.INACTIVE])
        Event.APPROVE_SELECTED_SETTINGS.log('{} {}'.format(
            request.method, request.path),
                                            user=request.user,
                                            obj=goal,
                                            support_request_id=sr_id)
        goal.approve_selected()

        serializer = serializers.GoalSettingSerializer(goal.approved_settings)

        return Response(serializer.data)
示例#10
0
    def selected_settings(self, request, pk=None, **kwargs):
        goal = self.get_object()

        if request.method == 'GET':
            serializer = serializers.GoalSettingSerializer(
                goal.selected_settings)
            return Response(serializer.data)

        sr_id = SupportRequest.get_current(request)
        data = request.data
        roa = None
        if request.method == 'POST':
            with transaction.atomic(
            ):  # So both the log and change get committed.
                check_state(Goal.State(goal.state),
                            [Goal.State.ACTIVE, Goal.State.INACTIVE])
                # If this field is specified and it is an update from an advisor, we create a record of advice.
                if 'record_of_advice' in request.data:
                    roa_data = data.pop('record_of_advice')
                    roa_ser = serializers.RecordOfAdviceSerializer(
                        data=roa_data)
                    roa_ser.initial_data['goal'] = goal.id
                    roa_ser.is_valid(raise_exception=True)
                    roa = roa_ser.save()

                serializer = serializers.GoalSettingWritableSerializer(
                    data=data, context={'request': request})
                serializer.is_valid(raise_exception=True)
                event = Event.SET_SELECTED_SETTINGS.log(
                    '{} {}'.format(self.request.method, self.request.path),
                    request.data,
                    user=request.user,
                    obj=goal,
                    support_request_id=sr_id)

                settings = serializer.save(goal=goal)

            if roa:
                roa.send_roa_generated_email()
            # We use the read-only serializer to send the settings object, not the update serializer.
            serializer = serializers.GoalSettingSerializer(settings)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data,
                            status=status.HTTP_200_OK,
                            headers=headers)

        elif request.method == 'PUT':
            with transaction.atomic(
            ):  # So both the log and change get committed.
                check_state(Goal.State(goal.state),
                            [Goal.State.ACTIVE, Goal.State.INACTIVE])
                # If this field is specified and it is an update from an advisor, we create a record of advice.
                if 'record_of_advice' in request.data:
                    roa_data = data.pop('record_of_advice')
                    roa_ser = serializers.RecordOfAdviceSerializer(
                        data=roa_data, context={'request': request})
                    roa_ser.initial_data['goal'] = goal.id
                    roa_ser.is_valid(raise_exception=True)
                    roa = roa_ser.save()

                settings = goal.selected_settings
                event = Event.UPDATE_SELECTED_SETTINGS.log(
                    '{} {}'.format(self.request.method, self.request.path),
                    request.data,
                    user=request.user,
                    obj=goal,
                    support_request_id=sr_id)
                serializer = serializers.GoalSettingWritableSerializer(
                    settings, data=data, partial=True)
                serializer.is_valid(raise_exception=True)
                settings = serializer.save(goal=goal)

            if roa:
                roa.send_roa_generated_email()
            # We use the read-only serializer to send the settings object, not the update serializer.
            serializer = serializers.GoalSettingSerializer(settings)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data,
                            status=status.HTTP_200_OK,
                            headers=headers)
示例#11
0
 def __create_goal(self):
     self.become_a_yogi = Goal()
     self.become_a_yogi.owner = self.user_marie_houana
     self.become_a_yogi.title = "Become a yogi"
     self.become_a_yogi.is_draft = False
     self.become_a_yogi.save()
示例#12
0
class Command(BaseCommand):
    help = \
        'Populates the database with example suggestions'

    def add_arguments(self, parser):
        pass

    def __migrate(self):
        if settings.DATABASES['default']['NAME'] == ":memory:":
            management.call_command('migrate', '--run-syncdb')
        else:
            management.call_command('migrate', '--run-syncdb')
            management.call_command(
                'makemigrations', 'goal', 'suggestion', 'review')
            management.call_command('migrate', '--fake-initial')

    def __make_global_user(self, username, password, first_name, last_name):
        user = User.objects.get_or_create(username=username)[0]
        user.set_password(password)
        user.first_name = first_name
        user.last_name = last_name
        user.save()

        global_user = GlobalUser()
        global_user.user = user
        global_user.save()

        return global_user

    def __create_superuser(self):
        management.call_command(
            'createsuperuser',
            '--noinput',
            username='******',
            email='*****@*****.**'
        )

        self.user_mnieber = self.__make_global_user(
            'mnieber', '***REMOVED***', 'Maarten', 'Nieber')

    def __create_users(self):
        self.user_anders_om = self.__make_global_user(
            "andersom", "***REMOVED***", "Anders", "Om")

        self.user_marie_houana = self.__make_global_user(
            "mhouana", "***REMOVED***", "Maria", "Houana")

    def __create_goal(self):
        self.become_a_yogi = Goal()
        self.become_a_yogi.owner = self.user_marie_houana
        self.become_a_yogi.title = "Become a yogi"
        self.become_a_yogi.is_draft = False
        self.become_a_yogi.save()

    def __create_members(self):
        self.yogi_mnieber = Member()
        self.yogi_mnieber.global_user = self.user_mnieber
        self.yogi_mnieber.goal = self.become_a_yogi
        self.yogi_mnieber.save()

        self.yogi_anders_om = Member()
        self.yogi_anders_om.global_user = self.user_anders_om
        self.yogi_anders_om.goal = self.become_a_yogi
        self.yogi_anders_om.save()

        self.yogi_marie_houana = Member()
        self.yogi_marie_houana.global_user = self.user_marie_houana
        self.yogi_marie_houana.goal = self.become_a_yogi
        self.yogi_marie_houana.save()

    def __create_suggestions(self):
        self.yoga_bend = Suggestion()
        self.yoga_bend.goal = self.become_a_yogi
        self.yoga_bend.owner = self.user_mnieber
        self.yoga_bend.is_draft = False
        self.yoga_bend.image = "suggestions/KroukTom-710x300-crop.jpg"
        self.yoga_bend.slug = "bend-backwards"
        self.yoga_bend.save()

        yoga_bend = Revision()
        yoga_bend.title = "Bend backwards"
        yoga_bend.description = yoga_bend_content
        yoga_bend.suggestion = self.yoga_bend
        yoga_bend.save()

        self.yoga_meditate = Suggestion()
        self.yoga_meditate.goal = self.become_a_yogi
        self.yoga_meditate.owner = self.user_mnieber
        self.yoga_meditate.is_draft = False
        self.yoga_meditate.image = "suggestions/Yoga_Nidra.jpg"
        self.yoga_meditate.slug = "meditate-often"
        self.yoga_meditate.save()

        yoga_meditate = Revision()
        yoga_meditate.title = "Meditate often"
        yoga_meditate.description = yoga_meditate_content
        yoga_meditate.suggestion = self.yoga_meditate
        yoga_meditate.save()

        self.yoga_twist = Suggestion()
        self.yoga_twist.goal = self.become_a_yogi
        self.yoga_twist.owner = self.user_anders_om
        self.yoga_twist.is_draft = False
        self.yoga_twist.image = "suggestions/MC_AM06_00_sized2.jpg"
        self.yoga_twist.slug = "keep-twisting"
        self.yoga_twist.save()

        self.rev_yoga_twist = Revision()
        self.rev_yoga_twist.title = "Keep twisting"
        self.rev_yoga_twist.description = yoga_twist_content
        self.rev_yoga_twist.suggestion = self.yoga_twist
        self.rev_yoga_twist.save()

        time.sleep(1)

        self.rev_yoga_twist_2 = Revision()
        self.rev_yoga_twist_2.title = "Keep twisting"
        self.rev_yoga_twist_2.description = yoga_twist_2_content
        self.rev_yoga_twist_2.suggestion = self.yoga_twist
        self.rev_yoga_twist_2.save()

        self.yoga_acrobatics = Suggestion()
        self.yoga_acrobatics.goal = self.become_a_yogi
        self.yoga_acrobatics.owner = self.user_marie_houana
        self.yoga_acrobatics.is_draft = False
        self.yoga_acrobatics.image = "suggestions/yoga-acrobats.jpg"
        self.yoga_acrobatics.slug = "yoga-acrobatics"
        self.yoga_acrobatics.save()

        yoga_acrobatics = Revision()
        yoga_acrobatics.title = "Acrobatics"
        yoga_acrobatics.description = yoga_acrobatics_content
        yoga_acrobatics.suggestion = self.yoga_acrobatics
        yoga_acrobatics.save()

    def __create_reviews(self):
        self.review_yoga_twist = Review()
        self.review_yoga_twist.owner = self.user_marie_houana
        self.review_yoga_twist.revision = self.rev_yoga_twist
        self.review_yoga_twist.rating = 2.5
        self.review_yoga_twist.description = "Not bad!"
        self.review_yoga_twist.is_draft = False
        self.review_yoga_twist.save()

        self.review_yoga_twist_2 = Review()
        self.review_yoga_twist_2.owner = self.user_mnieber
        self.review_yoga_twist_2.revision = self.rev_yoga_twist_2
        self.review_yoga_twist_2.rating = 4
        self.review_yoga_twist_2.description = "Good, good, good"
        self.review_yoga_twist_2.is_draft = False
        self.review_yoga_twist_2.save()

    def __create_comments(self):
        self.comment_1 = Comment()
        self.comment_1.owner = self.user_mnieber
        self.comment_1.body = "Thanks for the feedback"
        self.comment_1.review = self.review_yoga_twist
        self.comment_1.is_draft = False
        self.comment_1.save()

        self.comment_2 = Comment()
        self.comment_2.owner = self.user_anders_om
        self.comment_2.body = "I see your point"
        self.comment_2.review = self.review_yoga_twist
        self.comment_2.reply_to = self.comment_1
        self.comment_2.is_draft = False
        self.comment_2.save()

    def handle(self, *args, **options):
        management.call_command('initdb')
        self.__migrate()
        self.__create_superuser()
        self.__create_users()
        self.__create_goal()
        self.__create_members()
        self.__create_suggestions()
        self.__create_reviews()
        self.__create_comments()
示例#13
0
    def post(self, requests, *args, **kwargs):

        if "HTTP_X_HTTP_METHOD_OVERRIDE" in requests.META:
            if requests.META["HTTP_X_HTTP_METHOD_OVERRIDE"] == "DELETE":
                return self.delete(requests, *args, **kwargs)

        model = ujson.loads(requests.POST.get("model", '{}'))
        goal = Goal()
        goal.account = self.client.accounts.first()
        goal.name = model.get("name")
        goal.type = model.get("goalType")

        if "ETHICAL" in goal.type:
            goal.custom_portfolio_set = PortfolioSet.objects.get(name="Ethical")

        goal.account_type = model.get("accountType")
        goal.completion_date = datetime.strptime(
            model.get("goalCompletionDate"), '%Y%m%d%H%M%S')
        goal.allocation = model.get("allocation")
        goal.target = model.get("goalAmount", None)
        if goal.target is None:
            goal.target = 0
        goal.income = model.get("income", False)
        goal.save()
        return HttpResponse(ujson.dumps({"id": goal.pk}), content_type='application/json')
示例#14
0
    def withdraw(self, request, pk=None, **kwargs):
        goal = self.get_object()
        check_state(Goal.State(goal.state), Goal.State.ACTIVE)

        client = goal.account.primary_owner
        site = get_current_site(request)
        target_user = client.user
        sr_id = SupportRequest.get_current(request)

        if site.config().plaid_enabled:
            if not hasattr(target_user, 'invitation'):
                logger.error('Django user missing invitation')
                raise ValidationError(
                    'Client missing invitation, needed for withdrawals')
            else:
                if not hasattr(target_user.invitation, 'photo_verification'):
                    logger.error(
                        'Django user missing invitation.photo_verification')
                    raise ValidationError(
                        'Client missing invitation.photo_verification, needed for withdrawals'
                    )

        serializer = serializers.TransactionCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # Make sure the total amount for the goal is larger than the pending withdrawal amount.
        if goal.current_balance + 0.0000001 < serializer.validated_data[
                'amount']:
            emsg = "Goal's current balance: {} is less than the desired withdrawal amount: {}"
            raise SystemConstraintError(
                emsg.format(goal.current_balance,
                            serializer.validated_data['amount']))

        if site.config().plaid_enabled:
            # make sure user has connected a plaid_user
            plaid_user = getattr(target_user, 'plaid_user', False)
            if not plaid_user:
                logger.error(
                    'Withdrawal attempted by %s but no plaid_user found' %
                    target_user)
                raise ValidationError('Client has no plaid_user linked')

            if not serializer.validated_data.get('account_id', False):
                logger.error(
                    'No plaid account_id sent with withdrawal request')
                raise ValidationError(
                    'No plaid account_id sent with withdrawal request')

        transaction = serializer.save(from_goal=goal,
                                      reason=Transaction.REASON_WITHDRAWAL)

        if site.config().plaid_enabled:
            # execute transaction through stripe
            logger.info('Executing valid withdrawal request from %s for %s' %
                        (target_user, serializer.validated_data['amount']))
            stripe_token = get_stripe_account_token(
                target_user, serializer.validated_data['account_id'])
            try:
                transfer = execute_withdrawal(
                    target_user, serializer.validated_data['amount'],
                    stripe_token)
                if not transfer:
                    logger.error(
                        'Failed to execute withdrawal, marking Transaction %s failed'
                        % transaction)
                    transaction.status = Transaction.STATUS_FAILED
                    transaction.save()
                    return Response('Failed to charge account',
                                    status=status.HTTP_400_BAD_REQUEST)
                transaction.stripe_id = transfer.id
                transaction.save()
            except Exception as e:
                logger.error(
                    'Failed to execute withdrawal, marking Transaction %s failed'
                    % transaction)
                logger.error(e)
                transaction.status = Transaction.STATUS_FAILED
                transaction.save()
                return Response('Failed to charge account',
                                status=status.HTTP_400_BAD_REQUEST)
        else:
            # manual transfer, goal cash balance updated directly
            transaction.execute()

        Event.GOAL_WITHDRAWAL.log('{} {}'.format(request.method, request.path),
                                  request.data,
                                  user=request.user,
                                  obj=goal,
                                  support_request_id=sr_id)

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
示例#15
0
 def __create_goal(self):
     self.become_a_yogi = Goal()
     self.become_a_yogi.owner = self.user_marie_houana
     self.become_a_yogi.title = "Become a yogi"
     self.become_a_yogi.is_draft = False
     self.become_a_yogi.save()
示例#16
0
def CreateGoal(request):
    storage = messages.get_messages(request)
    storage.used = True
    if  not checkActiveGoal(request):
        if request.method=='POST':  
            form=GoalForm(request.POST)
            if form.is_valid():  
                goal = Goal()
                goal.deadline=form.cleaned_data.get('deadline')
                weightloser=WeightLoser.objects.get(user=request.user)
                goal.current_weight=float(str(form.cleaned_data['currWeight']))
                goal.target_weight=float(str(form.cleaned_data['currWeight'])) - float(str(form.cleaned_data['losepounds']))
                charity=Charity.objects.get(charityId=form.cleaned_data['charitylist'])
                goal = Goal(weightloser=weightloser,deadline=form.cleaned_data['deadline'],status='inprogress')
                goal.charity=charity
                goal.current_weight=float(str(form.cleaned_data['currWeight']))
                goal.target_weight=float(str(form.cleaned_data['currWeight'])) - float(str(form.cleaned_data['losepounds']))
                goal.benchmark=goal.current_weight
                goal.toLose=(goal.current_weight-goal.target_weight)
                goal.progress=0
                goal.save()
               # goal=Goal.objects.get(weightloser=weightloser) #check Ali 
                trackGoal=TrackGoal()
                trackGoal.goal=goal
                trackGoal.weight=goal.current_weight
                trackGoal.track_date=goal.creation_date
                trackGoal.save()
                setCheckActiveGoal(request,"T") # set that the user has active goal
                messages.success(request, 'the goal has been created, now it is time to get some sponsors!', 'Created_created')
                return HttpResponseRedirect('/inviteSponsor/')
            else:  #display the form when not valid
                return render_to_response('CreateGoal.html',{'form':form}, context_instance=RequestContext(request))
        else:    #Showing the form
            '''blank Form'''
            weightloser=WeightLoser.objects.get(user=request.user)
        
            form=GoalForm()
            context={'form':form}
            return render_to_response('CreateGoal.html',context, context_instance=RequestContext(request))
    else:
        messages.error(request, "You already have an active Goal, you can't have more than 1 active goal at a time", "Goal_Created")
        return HttpResponseRedirect('/addWeight/')
示例#17
0
class Command(BaseCommand):
    help = (
        'Populates the database with example suggestions'
    )

    def add_arguments(self, parser):
        pass

    def __migrate(self):
        if settings.DATABASES['default']['NAME'] == ":memory:":
            management.call_command('migrate', '--run-syncdb')
        else:
            management.call_command('migrate', '--run-syncdb')
            management.call_command(
                'makemigrations', 'goal', 'suggestion', 'review')
            management.call_command('migrate', '--fake-initial')

    def __make_global_user(self, username, password, first_name, last_name):
        user = User.objects.get_or_create(username=username)[0]
        user.set_password(password)
        user.first_name = first_name
        user.last_name = last_name
        user.save()

        global_user = GlobalUser()
        global_user.user = user
        global_user.save()

        return global_user

    def __create_superuser(self):
        management.call_command(
            'createsuperuser',
            '--noinput',
            username='******',
            email='*****@*****.**'
        )

        self.user_mnieber = self.__make_global_user(
            'mnieber', '***REMOVED***', 'Maarten', 'Nieber')

    def __create_users(self):
        self.user_anders_om = self.__make_global_user(
            "andersom", "***REMOVED***", "Anders", "Om")

        self.user_marie_houana = self.__make_global_user(
            "mhouana", "***REMOVED***", "Maria", "Houana")

    def __create_goal(self):
        self.become_a_yogi = Goal()
        self.become_a_yogi.owner = self.user_marie_houana
        self.become_a_yogi.title = "Become a yogi"
        self.become_a_yogi.is_draft = False
        self.become_a_yogi.save()

    def __create_members(self):
        self.yogi_mnieber = Member()
        self.yogi_mnieber.global_user = self.user_mnieber
        self.yogi_mnieber.goal = self.become_a_yogi
        self.yogi_mnieber.save()

        self.yogi_anders_om = Member()
        self.yogi_anders_om.global_user = self.user_anders_om
        self.yogi_anders_om.goal = self.become_a_yogi
        self.yogi_anders_om.save()

        self.yogi_marie_houana = Member()
        self.yogi_marie_houana.global_user = self.user_marie_houana
        self.yogi_marie_houana.goal = self.become_a_yogi
        self.yogi_marie_houana.save()

    def __create_suggestions(self):
        self.yoga_bend = Suggestion()
        self.yoga_bend.goal = self.become_a_yogi
        self.yoga_bend.owner = self.user_mnieber
        self.yoga_bend.is_draft = False
        self.yoga_bend.image = "suggestions/KroukTom-710x300-crop.jpg"
        self.yoga_bend.slug = "bend-backwards"
        self.yoga_bend.save()

        yoga_bend = Revision()
        yoga_bend.title = "Bend backwards"
        yoga_bend.description = yoga_bend_content
        yoga_bend.suggestion = self.yoga_bend
        yoga_bend.save()

        self.yoga_meditate = Suggestion()
        self.yoga_meditate.goal = self.become_a_yogi
        self.yoga_meditate.owner = self.user_mnieber
        self.yoga_meditate.is_draft = False
        self.yoga_meditate.image = "suggestions/Yoga_Nidra.jpg"
        self.yoga_meditate.slug = "meditate-often"
        self.yoga_meditate.save()

        yoga_meditate = Revision()
        yoga_meditate.title = "Meditate often"
        yoga_meditate.description = yoga_meditate_content
        yoga_meditate.suggestion = self.yoga_meditate
        yoga_meditate.save()

        self.yoga_twist = Suggestion()
        self.yoga_twist.goal = self.become_a_yogi
        self.yoga_twist.owner = self.user_anders_om
        self.yoga_twist.is_draft = False
        self.yoga_twist.image = "suggestions/MC_AM06_00_sized2.jpg"
        self.yoga_twist.slug = "keep-twisting"
        self.yoga_twist.save()

        self.rev_yoga_twist = Revision()
        self.rev_yoga_twist.title = "Keep twisting"
        self.rev_yoga_twist.description = yoga_twist_content
        self.rev_yoga_twist.suggestion = self.yoga_twist
        self.rev_yoga_twist.save()

        time.sleep(1)

        self.rev_yoga_twist_2 = Revision()
        self.rev_yoga_twist_2.title = "Keep twisting"
        self.rev_yoga_twist_2.description = yoga_twist_2_content
        self.rev_yoga_twist_2.suggestion = self.yoga_twist
        self.rev_yoga_twist_2.save()

        self.yoga_acrobatics = Suggestion()
        self.yoga_acrobatics.goal = self.become_a_yogi
        self.yoga_acrobatics.owner = self.user_marie_houana
        self.yoga_acrobatics.is_draft = False
        self.yoga_acrobatics.image = "suggestions/yoga-acrobats.jpg"
        self.yoga_acrobatics.slug = "yoga-acrobatics"
        self.yoga_acrobatics.save()

        yoga_acrobatics = Revision()
        yoga_acrobatics.title = "Acrobatics"
        yoga_acrobatics.description = yoga_acrobatics_content
        yoga_acrobatics.suggestion = self.yoga_acrobatics
        yoga_acrobatics.save()

    def __create_reviews(self):
        self.review_yoga_twist = Review()
        self.review_yoga_twist.owner = self.user_marie_houana
        self.review_yoga_twist.revision = self.rev_yoga_twist
        self.review_yoga_twist.rating = 2.5
        self.review_yoga_twist.description = "Not bad!"
        self.review_yoga_twist.is_draft = False
        self.review_yoga_twist.save()

        self.review_yoga_twist_2 = Review()
        self.review_yoga_twist_2.owner = self.user_mnieber
        self.review_yoga_twist_2.revision = self.rev_yoga_twist_2
        self.review_yoga_twist_2.rating = 4
        self.review_yoga_twist_2.description = "Good, good, good"
        self.review_yoga_twist_2.is_draft = False
        self.review_yoga_twist_2.save()

    def __create_comments(self):
        self.comment_1 = Comment()
        self.comment_1.owner = self.user_mnieber
        self.comment_1.body = "Thanks for the feedback"
        self.comment_1.review = self.review_yoga_twist
        self.comment_1.is_draft = False
        self.comment_1.save()

        self.comment_2 = Comment()
        self.comment_2.owner = self.user_anders_om
        self.comment_2.body = "I see your point"
        self.comment_2.review = self.review_yoga_twist
        self.comment_2.reply_to = self.comment_1
        self.comment_2.is_draft = False
        self.comment_2.save()

    def handle(self, *args, **options):
        management.call_command('initdb')
        self.__migrate()
        self.__create_superuser()
        self.__create_users()
        self.__create_goal()
        self.__create_members()
        self.__create_suggestions()
        self.__create_reviews()
        self.__create_comments()