コード例 #1
0
def quick_add(request):
    if request.method == 'POST' and request.is_ajax:
        # We need to create a copy of request.POST because it's immutable and
        # we need to convert the content of the Value field to mg/dL if the
        # user's glucose unit setting is set to mmol/L.
        post_values = request.POST.copy()
        if request.user.settings.glucose_unit.name == 'mmol/L':
            post_values['value'] = to_mg(post_values['value'])

        form = GlucoseCreateForm(post_values)
        if form.is_valid():
            user = request.user

            obj = form.save(commit=False)
            obj.user = user

            obj.record_date = datetime.now(tz=user.settings.time_zone).date()
            obj.record_time = datetime.now(tz=user.settings.time_zone).time()
            obj.save()

            logger.info('Quick Add by %s: %s', request.user,
                        post_values['value'])

            message = {'success': True}

            return HttpResponse(json.dumps(message))
        else:
            message = {'success': False, 'error': 'Invalid value.'}

            return HttpResponse(json.dumps(message))

    raise PermissionDenied
コード例 #2
0
ファイル: views.py プロジェクト: jcalazan/glucose-tracker
def quick_add(request):
    if request.method == 'POST' and request.is_ajax:
        # We need to create a copy of request.POST because it's immutable and
        # we need to convert the content of the Value field to mg/dL if the
        # user's glucose unit setting is set to mmol/L.
        post_values = request.POST.copy()
        if request.user.settings.glucose_unit.name == 'mmol/L':
            post_values['value'] = to_mg(post_values['value'])

        form = GlucoseCreateForm(post_values)
        if form.is_valid():
            user = request.user

            obj = form.save(commit=False)
            obj.user = user

            obj.record_date = datetime.now(tz=user.settings.time_zone).date()
            obj.record_time = datetime.now(tz=user.settings.time_zone).time()
            obj.save()

            logger.info('Quick Add by %s: %s', request.user, post_values['value'])

            message = {'success': True}

            return HttpResponse(json.dumps(message))
        else:
            message = {
                'success': False,
                'error': 'Invalid value.'
            }

            return HttpResponse(json.dumps(message))

    raise PermissionDenied
コード例 #3
0
ファイル: views.py プロジェクト: karmugsst/glucose-tracker
    def post(self, request, *args, **kwargs):
        # We need to create a copy of request.POST because it's immutable and
        # we need to convert the content of the Value field to mg/dL if the
        # user's glucose unit setting is set to mmol/L.
        request.POST = request.POST.copy()
        if request.user.settings.glucose_unit.name == 'mmol/L':
            request.POST['value'] = to_mg(request.POST['value'])

        return super(GlucoseUpdateView, self).post(request, *args, **kwargs)
コード例 #4
0
    def post(self, request, *args, **kwargs):
        # We need to create a copy of request.POST because it's immutable and
        # we need to convert the content of the Value field to mg/dL if the
        # user's glucose unit setting is set to mmol/L.
        request.POST = request.POST.copy()
        if request.user.settings.glucose_unit.name == 'mmol/L':
            request.POST['value'] = to_mg(request.POST['value'])

        return super(GlucoseUpdateView, self).post(request, *args, **kwargs)
コード例 #5
0
def filter_view(request):
    """
    Displays the glucose data table for the currently logged in user with
    filter options.

    The data is loaded by the GlucoseListJson view and rendered by the
    Datatables plugin via Javascript.
    """
    form = GlucoseFilterForm(request.user)
    form.fields['start_date'].initial = (datetime.now(
        tz=request.user.settings.time_zone) - timedelta(days=7)) \
        .date().strftime(DATE_FORMAT)
    form.fields['end_date'].initial = datetime.now(
        tz=request.user.settings.time_zone).date().strftime(DATE_FORMAT)

    data = reverse('glucose_list_json')

    if request.method == 'POST' and request.is_ajax:
        # We need to create a copy of request.POST because it's immutable and
        # we need to convert the content of the Value field to mg/dL if the
        # user's glucose unit setting is set to mmol/L.
        params = request.POST.copy()
        if request.user.settings.glucose_unit.name == 'mmol/L':
            # Only do the conversion if the values are not None or empty.
            if params['start_value']:
                params['start_value'] = to_mg(params['start_value'])
            if params['end_value']:
                params['end_value'] = to_mg(params['end_value'])

        # Create the URL query string and strip the last '&' at the end.
        data = ('%s?%s' % (reverse('glucose_list_json'), ''.join(
            ['%s=%s&' % (k, v) for k, v in params.iteritems()]))) \
            .rstrip('&')

        return HttpResponse(json.dumps(data), content_type='application/json')

    return render_to_response(
        'glucoses/glucose_filter.html',
        {
            'form': form,
            'data': data
        },
        context_instance=RequestContext(request),
    )
コード例 #6
0
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        form.full_clean()

        if form.is_valid():
            user = request.user
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.email = form.cleaned_data['email']
            user.save()

            user.settings.time_zone = form.cleaned_data['time_zone']

            glucose_unit = form.cleaned_data['glucose_unit']
            user.settings.glucose_unit = glucose_unit

            user.settings.default_category = form.cleaned_data[
                'default_category']

            glucose_low = form.cleaned_data['glucose_low']
            glucose_high = form.cleaned_data['glucose_high']
            glucose_target_min = form.cleaned_data['glucose_target_min']
            glucose_target_max = form.cleaned_data['glucose_target_max']

            # If user's glucose unit setting is set to mmol/L, convert the
            # values to mg/dL.
            if glucose_unit.name == 'mmol/L':
                glucose_low = to_mg(glucose_low)
                glucose_high = to_mg(glucose_high)
                glucose_target_min = to_mg(glucose_target_min)
                glucose_target_max = to_mg(glucose_target_max)

            user.settings.glucose_low = glucose_low
            user.settings.glucose_high = glucose_high
            user.settings.glucose_target_min = glucose_target_min
            user.settings.glucose_target_max = glucose_target_max
            user.settings.save()

            logger.info('Account Settings updated by %s', user)

            return self.form_valid(form)
        else:
            return self.form_invalid(form)
コード例 #7
0
def import_glucose_from_csv(user, csv_file):
    """
    Import glucose CSV data.

    We'll process all rows first and create Glucose model objects from them
    and perform a bulk create. This way, no records will be inserted unless
    all records are good.

    Also note that we're using splitlines() to make sure 'universal newlines'
    is used.

    Assumed order: value, category, record_date, record_time, notes
    """
    csv_data = []
    reader = csv.reader(csv_file.read().splitlines(),
                        delimiter=',',
                        quotechar='"')
    for row in reader:
        csv_data.append([item.strip() for item in row])

    glucose_objects = []

    # Check if headers exists. Skip the first entry if true.
    header_check = ['value', 'category', 'date', 'time']
    first_row = [i.lower().strip() for i in csv_data[0]]
    if all(i in first_row for i in header_check):
        csv_data = csv_data[1:]

    for row in csv_data:
        # Let's do an extra check to make sure the row is not empty.
        if row:
            try:
                category = Category.objects.get(name__iexact=row[1].strip())
            except ObjectDoesNotExist:
                category = Category.objects.get(
                    name__iexact='No Category'.strip())

            # Since we always store the value in mg/dL format in the db, we need
            # to make sure we convert it here if the user's setting is set to
            # mmol/L.
            if user.settings.glucose_unit.name == 'mmol/L':
                value = int(to_mg(row[0]))
            else:
                value = int(row[0])

            glucose_objects.append(
                Glucose(
                    user=user,
                    value=value,
                    category=category,
                    record_date=datetime.strptime(row[2], DATE_FORMAT),
                    record_time=datetime.strptime(row[3], TIME_FORMAT),
                    notes=row[4],
                ))

    Glucose.objects.bulk_create(glucose_objects)
コード例 #8
0
ファイル: views.py プロジェクト: Wassimply/glucose-tracker
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        form.full_clean()

        if form.is_valid():
            user = request.user
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.email = form.cleaned_data['email']
            user.save()

            user.settings.time_zone = form.cleaned_data['time_zone']

            glucose_unit = form.cleaned_data['glucose_unit']
            user.settings.glucose_unit = glucose_unit

            user.settings.default_category = form.cleaned_data['default_category']

            glucose_low = form.cleaned_data['glucose_low']
            glucose_high = form.cleaned_data['glucose_high']
            glucose_target_min = form.cleaned_data['glucose_target_min']
            glucose_target_max = form.cleaned_data['glucose_target_max']

            # If user's glucose unit setting is set to mmol/L, convert the
            # values to mg/dL.
            if glucose_unit.name == 'mmol/L':
                glucose_low = to_mg(glucose_low)
                glucose_high = to_mg(glucose_high)
                glucose_target_min = to_mg(glucose_target_min)
                glucose_target_max = to_mg(glucose_target_max)

            user.settings.glucose_low = glucose_low
            user.settings.glucose_high = glucose_high
            user.settings.glucose_target_min = glucose_target_min
            user.settings.glucose_target_max = glucose_target_max
            user.settings.save()

            logger.info('Account Settings updated by %s', user)

            return self.form_valid(form)
        else:
            return self.form_invalid(form)
コード例 #9
0
ファイル: views.py プロジェクト: jcalazan/glucose-tracker
def filter_view(request):
    """
    Displays the glucose data table for the currently logged in user with
    filter options.

    The data is loaded by the GlucoseListJson view and rendered by the
    Datatables plugin via Javascript.
    """
    form = GlucoseFilterForm(request.user)
    form.fields['start_date'].initial = (datetime.now(
        tz=request.user.settings.time_zone) - timedelta(days=7))\
        .date().strftime(DATE_FORMAT)
    form.fields['end_date'].initial = datetime.now(
        tz=request.user.settings.time_zone).date().strftime(DATE_FORMAT)

    data = reverse('glucose_list_json')

    if request.method == 'POST' and request.is_ajax:
        # We need to create a copy of request.POST because it's immutable and
        # we need to convert the content of the Value field to mg/dL if the
        # user's glucose unit setting is set to mmol/L.
        params = request.POST.copy()
        if request.user.settings.glucose_unit.name == 'mmol/L':
            # Only do the conversion if the values are not None or empty.
            if params['start_value']:
                params['start_value'] = to_mg(params['start_value'])
            if params['end_value']:
                params['end_value'] = to_mg(params['end_value'])

        # Create the URL query string and strip the last '&' at the end.
        data = ('%s?%s' % (reverse('glucose_list_json'), ''.join(
            ['%s=%s&' % (k, v) for k, v in params.iteritems()])))\
            .rstrip('&')

        return HttpResponse(json.dumps(data), content_type='application/json')

    return render_to_response(
        'glucoses/glucose_filter.html',
        {'form': form, 'data': data},
        context_instance=RequestContext(request),
    )
コード例 #10
0
ファイル: utils.py プロジェクト: Wassimply/glucose-tracker
def import_glucose_from_csv(user, csv_file):
    """
    Import glucose CSV data.

    We'll process all rows first and create Glucose model objects from them
    and perform a bulk create. This way, no records will be inserted unless
    all records are good.

    Also note that we're using splitlines() to make sure 'universal newlines'
    is used.

    Assumed order: value, category, record_date, record_time, notes
    """
    csv_data = []
    reader = csv.reader(csv_file.read().splitlines(), delimiter=',',
                        quotechar='"')
    for row in reader:
        csv_data.append([item.strip() for item in row])

    glucose_objects = []

    # Check if headers exists. Skip the first entry if true.
    header_check = ['value', 'category', 'date', 'time']
    first_row = [i.lower().strip() for i in csv_data[0]]
    if all(i in first_row for i in header_check):
        csv_data = csv_data[1:]

    for row in csv_data:
        # Let's do an extra check to make sure the row is not empty.
        if row:
            try:
                category = Category.objects.get(name__iexact=row[1].strip())
            except ObjectDoesNotExist:
                category = Category.objects.get(name__iexact='No Category'.strip())

            # Since we always store the value in mg/dL format in the db, we need
            # to make sure we convert it here if the user's setting is set to
            # mmol/L.
            if user.settings.glucose_unit.name == 'mmol/L':
                value = int(to_mg(row[0]))
            else:
                value = int(row[0])

            glucose_objects.append(Glucose(
                user=user,
                value=value,
                category=category,
                record_date=datetime.strptime(row[2], DATE_FORMAT),
                record_time=datetime.strptime(row[3], TIME_FORMAT),
                notes=row[4],
            ))

    Glucose.objects.bulk_create(glucose_objects)