コード例 #1
0
ファイル: views.py プロジェクト: dgets/lasttime
def sub_class_details(request, class_id):
    """
    View shows the details for a given classification of substances, including
    the substances classified under it currently.

    :param request:
    :param class_id:
    :return:
    """

    class_details = SubstanceClass.objects.get(id=class_id)
    substances_in_class = Substance.objects.filter(sub_class=class_details.id)

    paginator = Paginator(substances_in_class, 10)  # 15 admins per page

    page = request.GET.get('page')
    subs = paginator.get_page(page)

    return render(
        request, 'subadd/class_details.html',
        MiscMethods.add_pagination_info(
            MiscMethods.add_header_info({
                'class_details': class_details,
                'substances': subs,
            }), subs))
コード例 #2
0
ファイル: views.py プロジェクト: dgets/lasttime
def index(request):
    all_subs = Substance.objects.all()
    filtered_subs = []
    context = {}

    for sub in all_subs:
        if Usage.objects.filter(sub=sub.pk, user=request.user).exists():
            print("Adding " + str(sub))
            filtered_subs.append(sub)

    print("Filtered subs: " + str(filtered_subs))

    paginator = Paginator(filtered_subs, 15)  # 15 admins per page

    page = request.GET.get('page')
    subs = paginator.get_page(page)

    print("subs: " + str(subs))

    context = {'relevant_subs': subs}

    return render(
        request, 'dataview/index.html',
        MiscMethods.add_pagination_info(MiscMethods.add_header_info(context),
                                        subs))
コード例 #3
0
def per_app_docs(request):
    topics = SpecificViewHelpTopic.objects.all()
    paginator = Paginator(topics, 15)

    page = request.GET.get('page')
    topics_set = paginator.get_page(page)

    return render(request, 'dox/sv_index.html', MiscMethods.add_pagination_info(
        MiscMethods.add_header_info({'topics' : topics,}), topics_set))
コード例 #4
0
ファイル: views.py プロジェクト: dgets/lasttime
def add_sub_class(request):
    """
    View provides the ability to add a new SubstanceClass.

    :param request:
    :return:
    """

    sub_classes = SubstanceClass.objects.all()

    if request.method != 'POST':
        add_sub_class_form = SubstanceClassForm()

        return render(
            request, 'subadd/add_class.html',
            MiscMethods.add_header_info({
                'substance_class':
                None,
                'substance_classes':
                sub_classes,
                'add_sub_class_form':
                add_sub_class_form
            }))

    else:
        add_sub_class_rec = SubstanceClass(name=request.POST['name'],
                                           desc=request.POST['desc'])

        try:
            add_sub_class_rec.save()

            context = {
                'user_message': "Substance classification added successfully!",
                'substance_classes': sub_classes,
            }

        except Exception as e:
            error_message = "Unable to save to db: " + str(
                e) + " admin: " + str(add_sub_class_rec)

            add_sub_class_form = SubstanceClassForm({
                'name':
                request.POST['name'],
                'desc':
                request.POST['desc'],
            })

            context = {
                'add_sub_class_form': add_sub_class_form,
                'error_message': error_message,
                'substance_classes': sub_classes,
            }

        return render(request, 'subadd/add_class.html',
                      MiscMethods.add_header_info(context))
コード例 #5
0
ファイル: views.py プロジェクト: dgets/lasttime
def addentry(request):
    """
    Another version of the above substance data entry form, this one is for
    usage when there was an error in validation or submission and processing
    of the previous form; this one comes pre-filled with whatever data the
    user had previously submitted.  Hands things off to addentry template,
    if there is an issue in saving the database record from the previous
    entry, otherwise it stuffs everything in the database where it needs to
    go and sends the user back to the index template in order to see the
    substances summary so that they can verify that their addition has been
    added.

    :param request:
    :return:
    """

    try:
        substance = Substance(
            common_name=request.POST['common_name'],
            sci_name=request.POST['sci_name'],
            half_life=request.POST['half_life'],
            active_half_life=request.POST['active_half_life'],
            lipid_solubility=request.POST.get('lipid_solubility', False),
            units=request.POST['units'])

        # we'll need to do validation here, of course

    except:
        context = {}
        context[
            'error_message'] = "Please navigate to addentry (here) only from the links."

        return render(request, 'subadd/add.html',
                      MiscMethods.add_header_info(context))

    try:
        if substance.lipid_solubility != False:
            substance.lipid_solubility = True

        substance.save()
    except Exception as ex:
        context = {}
        context['error_message'] = "Unable to save record to database (" + str(
            ex) + ")!"
        context['substance'] = substance

        return render(request, 'subadd/add.html',
                      MiscMethods.add_header_info(context))

    return render(
        request, 'subadd/index.html',
        MiscMethods.add_header_info({'all_subs': Substance.objects.all()}))
コード例 #6
0
ファイル: views.py プロジェクト: dgets/lasttime
def dump_interval_graph_data(request, sub_id):
    """
    View does the same as the above one, except for the intervals between
    administrations data subset.

    TODO: utilize check_intervals_for_extremes_from_average in dataview_support

    :param request:
    :param sub_id:
    :return:
    """

    usages = Usage.objects.filter(sub=sub_id,
                                  user=request.user).order_by("timestamp")

    timespans = []
    prev_time = None
    # tmp_dt = None
    max_span = datetime.timedelta(0)
    for use in usages:
        # localization needed?
        if MiscMethods.is_localization_needed(use.timestamp):
            tmp_dt = MiscMethods.localize_timestamp(use.timestamp)
        else:
            tmp_dt = use.timestamp

        if prev_time is not None:
            # current_delta = datetime.timedelta
            current_delta = tmp_dt - prev_time
            timespans.append(int(current_delta.total_seconds() / 3600))

            if current_delta > max_span:
                max_span = current_delta

        prev_time = tmp_dt

    scale_factor = 1  # get_graph_normalization_divisor(max_span.total_seconds(), 72)
    # convert this to minutes
    for cntr in range(0, len(timespans)):
        timespans[cntr] = timespans[cntr]

    timespans = dataview_support.check_for_extremes_from_average(timespans)

    return HttpResponse(json.dumps({
        'scale_factor': scale_factor,
        'timespans': timespans
    }),
                        content_type='application/json')
コード例 #7
0
def add(request):
    """
    View for adding a particular administration record.  Passes the view off
    to the add_entry template.

    :param request:
    :return:
    """

    substances = Substance.objects.all()
    usual_suspects = UsualSuspect.objects.all()

    mydata = []

    add_administration_form = UsageForm()

    for sub in substances:
        mydata.append({
            'name': sub.common_name,
            'id': sub.id,
        })

    context = {
        'mydata': mydata,
        'timestamp': "YYYY-mm-dd HH:MM:SS",
        # 'timestamp': datetime.now(),  # the other option
        'usual_suspects': usual_suspects,
        'add_admin_form': add_administration_form,
    }

    return render(request, 'recadm/add_entry.html',
                  MiscMethods.add_header_info(context))
コード例 #8
0
def index(request):
    """
    View displays the topics links for everything available, paginated if
    necessary.

    :param request:
    :return:
    """

    topics = MainHelpTopic.objects.all()
    paginator = Paginator(topics, 15)

    page = request.GET.get('page')
    topics_set = paginator.get_page(page)

    return render(request, 'dox/index.html', MiscMethods.add_pagination_info(
        MiscMethods.add_header_info({'topics': topics_set,}), topics_set))
コード例 #9
0
def index(request):
    """
    View shows the details of administrations; it will, at some point,
    obviously have to be chopped down for a reasonable subset of the
    list, but it's good for testing purposes.  Passes the view off via
    the recadm/index template.

    :param request:
    :return:
    """

    recent_administrations = Usage.objects.filter(user=request.user).order_by(
        'sub', '-timestamp')
    paginator = Paginator(recent_administrations, 15)  # 15 admins per page

    page = request.GET.get('page')
    administrations = paginator.get_page(page)

    mydata = []
    for administration in administrations:  # recent_administrations:
        # localize timestamp?
        if MiscMethods.is_localization_needed(administration.timestamp):
            local_dt = MiscMethods.localize_timestamp(administration.timestamp)
        else:
            local_dt = administration.timestamp

        mydata.append({
            'ts': local_dt,
            'id': administration.id,
            'dosage': administration.dosage,
            'units': administration.sub.units,
            'substance_name': administration.sub,
        })

    context = {
        'mydata': mydata,
        'user': request.user,
        'administrations': administrations,
    }

    return render(
        request, 'recadm/index.html',
        MiscMethods.add_pagination_info(MiscMethods.add_header_info(context),
                                        administrations))
コード例 #10
0
def add_usual_suspect(request):
    """
    Provides capability for adding a usual suspect to the database.

    :param request:
    :return:
    """

    if request.method != 'POST':
        # display the form and get what we need for a new US entry
        # add_usual_suspect_form = UsualSuspectForm()

        return render(
            request, 'recadm/add_usual_suspect.html',
            MiscMethods.add_header_info({
                'add_usual_suspect_form':
                UsualSuspectForm(),
            }))

    else:
        context = {}
        # validate (if necessary) and save the form contents
        new_us = UsualSuspect()

        new_us.name = request.POST['name']
        new_us.sub_id = Substance.objects.get(id=request.POST['sub_id'])
        new_us.dosage = request.POST['dosage']
        new_us.notes = request.POST['notes']

        try:
            new_us.save()
        except Exception as ex:
            context[
                'error_message'] = "Unable to save new usual suspect: " + str(
                    ex)
            context['add_usual_suspect_form'] = UsualSuspectForm(
                instance=new_us)

            return render(request, 'recadm/add_usual_suspect.html',
                          MiscMethods.add_header_info(context))

        context['user_message'] = "Saved new usual suspect."

        return redirect('/recadm/')
コード例 #11
0
ファイル: views.py プロジェクト: dgets/lasttime
def create_user_interface(request):
    """
    Method is utilized for the user creation page.

    :param request:
    :return:
    """

    if request.method == "POST":
        context = {}

        try:
            user = User.objects.create_user(request.POST['username'],
                                            request.POST['email'],
                                            request.POST['password'])
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user.tz = Const.Time_Zone  # obviously this will need to be changed when we add user TZ selection
            user.save(
            )  # this will need to be in an error handling block at some point here
        except Exception as ex:
            create_user_form = NewUserForm
            return render(
                request, 'home/create_user.html',
                MiscMethods.add_header_info({
                    'create_user_form':
                    create_user_form,
                    'error_message':
                    "Error saving: " + str(ex),
                }))

        context['username'] = user.username

        return render(request, 'home/user_created.html',
                      MiscMethods.add_header_info(context))
    else:
        create_user_form = NewUserForm()

        return render(
            request, 'home/create_user.html',
            MiscMethods.add_header_info({'create_user_form':
                                         create_user_form}))
コード例 #12
0
def detail(request, topic_id):
    """
    Provides the details on any particular administration's notes, primarily
    (or maybe solely) linked via the index page's summary of different
    administration details.

    :param request:
    :param topic_id:
    :return:
    """

    try:
        admin_details = Usage.objects.get(id=topic_id, user=request.user)
    except Usage.DoesNotExist:
        return render(
            request, 'recadm/details.html',
            MiscMethods.add_header_info({
                'error_message':
                "The Usage records you requested do not seem to exist...",
            }))

    # localization needed?
    if MiscMethods.is_localization_needed(admin_details.timestamp):
        tmp_dt = MiscMethods.localize_timestamp(admin_details.timestamp)
    else:
        tmp_dt = admin_details.timestamp

    context = {
        'sub': admin_details.sub,
        'dosage': admin_details.dosage,
        'units': admin_details.sub.units,
        'timestamp': tmp_dt,
        'notes': admin_details.notes,
        'admin_id': admin_details.id,
    }

    return render(request, 'recadm/details.html',
                  MiscMethods.add_header_info(context))
コード例 #13
0
ファイル: views.py プロジェクト: dgets/lasttime
def index(request):
    """
    View provides a listing of all substances in the database; passes the
    information on to the index template for rendering.

    :param request:
    :return:
    """

    all_subs = Substance.objects.all()
    paginator = Paginator(all_subs, 15)  # 15 admins per page

    page = request.GET.get('page')
    subs = paginator.get_page(page)

    context = {
        'all_subs': subs,
    }

    return render(
        request, 'subadd/index.html',
        MiscMethods.add_pagination_info(MiscMethods.add_header_info(context),
                                        subs))
コード例 #14
0
def detail(request, topic_id):
    """
    Displays the detailed information for whatever link was selected in the
    index view, above.

    :param request:
    :param topic_id:
    :return:
    """

    topic_info = {}
    topic_info['primary'] = MainHelpTopic.objects.get(id=topic_id)
    topic_info['supporting'] = MainHelpTopicDetail.objects.filter(topic=topic_id)

    return render(request, 'dox/detail.html', MiscMethods.add_header_info(topic_info))
コード例 #15
0
ファイル: views.py プロジェクト: dgets/lasttime
def edit_sub(request):
    """
    View provides the capability to edit a substance's details.

    :param request:
    :param substance_id:
    :return:
    """

    context = {}

    if request.method == 'POST':
        # print(request.POST['sub_to_edit'])
        try:
            substance_to_edit = Substance.objects.get(
                id=request.POST['sub_to_edit'])  # SubstanceForm

        except Exception as ex:
            context['substances'] = Substance.objects.all()
            context['error_message'] = "No substance selected for editing!"

            return render(request, 'subadd/edit_sub.html',
                          MiscMethods.add_header_info(context))

        # substance_form = substance
        context['substance_form'] = SubstanceForm(instance=substance_to_edit)
        context['sub_id'] = request.POST['sub_to_edit']

        return render(request, 'subadd/edit_sub.html',
                      MiscMethods.add_header_info(context))

    else:
        context['substances'] = Substance.objects.all()

        return render(request, 'subadd/edit_sub.html',
                      MiscMethods.add_header_info(context))
コード例 #16
0
ファイル: views.py プロジェクト: dgets/lasttime
def edited_sub(request, sub_id):
    """
    View saves the [presumably] changed information from the previous edit_sub
    view's Substance record.

    :param request:
    :param sub_id:
    :return:
    """

    context = {}

    edited_substance = Substance.objects.get(id=sub_id)

    # print(str(edited_substance))
    # print("\n---\n")

    edited_substance.common_name = request.POST['common_name']
    edited_substance.sci_name = request.POST['sci_name']
    edited_substance.half_life = request.POST['half_life']
    edited_substance.active_half_life = request.POST['active_half_life']
    # edited_substance.lipid_solubility = request.POST['lipid_solubility']
    edited_substance.lipid_solubility = request.POST.get(
        'lipid_solubility', False)
    # don't forget to check the measurement value, detc

    # if edited_substance.lipid_solubility != False:
    #     edited_substance.lipid_solubility = True

    context['edited_substance'] = edited_substance

    try:
        edited_substance.save()

        context[
            'user_message'] = "Saved this record for " + edited_substance.common_name + "."

    except Exception as ex:
        context[
            'error_message'] = "Unable to save record for " + edited_substance.common_name + ": " + str(
                ex)

    # print(str(edited_substance))

    return render(request, 'subadd/edited.html',
                  MiscMethods.add_header_info(context))
コード例 #17
0
ファイル: views.py プロジェクト: dgets/lasttime
def add(request):
    """
    View provides an empty form with the relevant fields (see forms.py) needing
    to be filled out by the user in order to record a new substance.  Passes
    the form off to add.html for rendering.

    :param request:
    :return:
    """

    add_sub_form = SubstanceForm()

    return render(
        request, 'subadd/add.html',
        MiscMethods.add_header_info({
            'substance': None,
            'add_sub_form': add_sub_form
        }))
コード例 #18
0
def delete_admin(request):
    """
    Provides capability for deleting an administration (or several).

    :param request:
    :return:
    """

    context = {}

    if request.method != 'POST':
        # display the administrations available for deletion
        context['admins'] = Usage.objects.filter(user=request.user)

    elif 'admin_checks' in request.POST:
        # confirm and delete the checked administrations
        # first build a set of the administrations
        # admins = []
        context['selected_admins'] = []
        context['selected_admin_ids'] = []
        for admin in request.POST.getlist('admin_checks'):
            tmp_usage = Usage.objects.get(id=admin)
            context['selected_admins'].append(str(tmp_usage))
            context['selected_admin_ids'].append(tmp_usage.id)

    elif 'delete_confirmed' in request.POST:
        # now we will go ahead and wipe what has been confirmed for deletion
        # for use_id in context['selected_admin_ids']:
        for use_id in request.POST.getlist('selected_admin_ids'):
            print("Deleting administration: " + use_id)
            Usage.objects.filter(id=use_id).delete()

        context['user_message'] = "Administrations deleted!"
        context['admins'] = Usage.objects.filter(user=request.user)

    else:
        # whayit
        context['error_message'] = "Whayit?"

    return render(request, 'recadm/delete_admin.html',
                  MiscMethods.add_header_info(context))
コード例 #19
0
def save_usual_suspect_admin(request):
    """
    Saves the administration of a usual_suspect from the 'add' view above.

    :param request:
    :return:
    """

    context = {}

    if request.method != 'POST':
        # we have some sort of funky error here
        context['error_message'] = "We had some sort of funky error here."

    else:
        us = UsualSuspect.objects.get(id=request.POST['us_value'])

        # save our administration here
        new_usage = Usage()
        new_usage.user = request.user
        new_usage.sub = us.sub_id
        new_usage.dosage = us.dosage
        new_usage.notes = us.notes
        if request.POST['timestamp'] == "" or request.POST[
                'timestamp'] == "YYYY-mm-dd HH:MM:SS":
            new_usage.timestamp = datetime.now()
        else:
            new_usage.timestamp = datetime.strptime(request.POST['timestamp'],
                                                    '%Y-%m-%d %H:%M:%S')

        try:
            new_usage.save()

            context['user_message'] = "Saved usual suspect administration."
        except Exception as e:
            context[
                'error_message'] = "Houston, we have a friggin' problem: " + str(
                    e)

    return render(request, 'recadm/usual_suspect_admin_added.html',
                  MiscMethods.add_header_info(context))
コード例 #20
0
ファイル: views.py プロジェクト: dgets/lasttime
def detail(request, substance_id):
    """
    View provides details on any particular substance record.  Hands things
    off to the detail template for rendering.

    :param request:
    :param substance_id:
    :return:
    """

    context = {}

    try:
        # substance = get_object_or_404(Substance, pk=substance_id)
        context['substance'] = Substance.objects.get(pk=substance_id)
    except Substance.DoesNotExist:
        # raise Http404("Substance does not exist :|")
        context[
            'error_message'] = "The substance you are looking for does not seem to exist..."

    return render(request, 'subadd/detail.html',
                  MiscMethods.add_header_info(context))
コード例 #21
0
ファイル: views.py プロジェクト: dgets/lasttime
def sclasses(request):
    """
    Method provides selection for classes to view the detailed statistics
    breakdown of.

    :param request:
    :return:
    """

    if request.method != 'POST':
        # if there are no classes we should return an error_message to user
        sub_classes = SubstanceClass.objects.all()

        return render(request, 'dataview/sclasses.html',
                      MiscMethods.add_header_info({
                          'classes': sub_classes,
                      }))

    else:
        # return redirect('subadd:sub_class_details', class_id=request.POST['class_destination'])
        return redirect('dataview:class_data_summary',
                        class_id=request.POST['class_destination'])
コード例 #22
0
def save_admin(request):
    """
    View is called when add_entry is submitted and passes the data off here in
    order to save it to the database.  It returns the viewer back to the index
    template, in order to see the results of the database addition at the top
    of the administration records.

    :param request:
    :return:
    """

    if request.method == "POST":
        add_administration_form = UsageForm({
            'sub':
            request.POST['sub'],
            'dosage':
            request.POST['dosage'],
            'timestamp':
            request.POST['timestamp'],
            'notes':
            request.POST['notes']
        })
        # localize the timestamp
        central_tz = timezone(Const.Time_Zone)
        timestamp = central_tz.localize(
            datetime.strptime(request.POST['timestamp'], '%Y-%m-%d %H:%M:%S'))
        print(str(timestamp))
        new_administration = Usage(
            sub=Substance.objects.get(id=request.POST['sub']),
            user=request.user,
            dosage=request.POST['dosage'],
            timestamp=timestamp,
            notes=request.POST['notes'])

        try:
            new_administration.save()
        except Exception as e:
            error_message = "Unable to save to db: " + str(
                e) + "admin: " + str(new_administration)

            context = {
                'add_admin_form': add_administration_form,
                'error_message': error_message,
            }

            return render(request, 'recadm/add_entry.html',
                          MiscMethods.add_header_info(context))

    # code for the successful save of the record and return to the index
    # follows here
    mydata = []

    recent_administrations = Usage.objects.filter(
        user=request.user).order_by('-timestamp')
    paginator = Paginator(recent_administrations, 15)  # 15 admins per page

    page = request.GET.get('page')
    administrations = paginator.get_page(page)

    for administration in administrations:
        # localization needed?
        if MiscMethods.is_localization_needed(administration.timestamp):
            tmp_dt = MiscMethods.localize_timestamp(administration.timestamp)
        else:
            tmp_dt = administration.timestamp

        mydata.append({
            'ts': tmp_dt,
            'id': administration.id,
            'dosage': administration.dosage,
            'substance_name': administration.sub,
        })

    context = {
        'mydata': mydata,
        'administrations': administrations,
    }

    return render(request, 'recadm/index.html',
                  MiscMethods.add_header_info(context))
コード例 #23
0
def prune_database_by_date(request):
    """
    Provides capability for deleting the administrations from the database that
    are older than a specified date/time.  Only for the current user, of
    course.

    :param request:
    :return:
    """

    context = {}

    if request.method != 'POST':
        context['all_subs'] = Substance.objects.all()

    elif 'need_verification' in request.POST:
        # context['all_subs'] = Substance.objects.all()

        try:
            prune_prior_to_date = datetime.strptime(
                request.POST['prune_prior_to_date'], '%Y-%m-%d %H:%M:%S')
        except Exception as e:
            context['error_message'] = "Could not parse date: " + str(e)
            return render(request, 'recadm/prune_database_by_date.html',
                          MiscMethods.add_header_info(context))

        admins = Usage.objects.filter(
            user=request.user, sub=request.POST['sub_to_prune'], timestamp__lte=prune_prior_to_date).\
            order_by('-timestamp')

        paginator = Paginator(admins, 15)  # 15 admins per page

        page = request.GET.get('page')
        administrations = paginator.get_page(page)

        context['administrations'] = administrations
        context['need_verification'] = True
        context['user_message'] = "Please verify pruning the database prior to " + request.POST['prune_prior_to_date'] \
            + ", as this is irreversible!"
        context['prune_prior_to_date'] = str(prune_prior_to_date)
        context['sub_to_prune'] = request.POST['sub_to_prune']

        return render(
            request, 'recadm/prune_database_by_date.html',
            MiscMethods.add_pagination_info(
                MiscMethods.add_header_info(context), administrations))

    elif 'verified' in request.POST:
        prune_prior_to_date = datetime.strptime(
            request.POST['prune_prior_to_date'], '%Y-%m-%d %H:%M:%S')

        usages = Usage.objects.filter(
            user=request.user,
            sub=request.POST['sub_to_prune'],
            timestamp__lte=prune_prior_to_date).delete()

        context['user_message'] = str(len(usages)) + " entries prior to " + request.POST['prune_prior_to_date'] + \
            " have been deleted."
        context['verified'] = True

    else:
        context['all_subs'] = Substance.objects.all()
        context[
            'error_message'] = "You did not verify deleting the database entries for pruning!"

    return render(request, 'recadm/prune_database_by_date.html',
                  MiscMethods.add_header_info(context))
コード例 #24
0
def get_weed_stats(usages, active_half_life):
    """
    We're working with weed, let's give this a shot based on the information
    available at
    https://www.mayocliniclabs.com/test-info/drug-book/marijuana.html FWIW
    we're just going to base our projection on the average of the last 2 weeks
    of usage.

    :param usages:
    :param active_half_life:
    :return:
    """

    weeks_averaged = 2
    relevant_dt = MiscMethods.localize_timestamp(datetime.datetime.now())
    elimination_data = {
        'full': float(active_half_life) * 5.7,
        'detectable': None,
        'relevant_since':
        relevant_dt - datetime.timedelta(weeks=weeks_averaged),
        'last_usage': usages.first(),
        'uses': len(usages)
    }

    # localize the following?
    last_usage_dt = elimination_data['last_usage'].timestamp
    uses_dt = elimination_data['uses'].timestamp

    if MiscMethods.is_localization_needed(last_usage_dt):
        last_usage_dt = MiscMethods.localize_timestamp(last_usage_dt)
    if MiscMethods.is_localization_needed(uses_dt):
        uses_dt = MiscMethods.localize_timestamp(uses_dt)

    # note that half-life durations here (not flat day count) are calculated @ 5.7 * half-life, as in the
    # standard non-lipid-soluble substances; detectable metabolites will be out of the system sooner (hence
    # the less precise flat day count)
    if elimination_data['uses'] <= weeks_averaged:
        # single use: detectable for a standard half-life duration
        elimination_data['full'] = last_usage_dt + datetime.timedelta(
            hours=int(elimination_data['full']))
        elimination_data['detectable'] = last_usage_dt + datetime.timedelta(
            days=3)

    elif elimination_data['uses'] <= (weeks_averaged * 4):
        # moderate use: detectable for standard half-life * 5/3, _or_ 5 days
        elimination_data['full'] = last_usage_dt + datetime.timedelta(
            hours=int(elimination_data['full'] * (5 / 3)))
        elimination_data['detectable'] = last_usage_dt + datetime.timedelta(
            days=5)

    elif elimination_data['uses'] <= (weeks_averaged * 7):
        # heavy use: detectable for standard half-life * 10/3, _or_ 10 days
        elimination_data['full'] = last_usage_dt + datetime.timedelta(
            hours=int(elimination_data['full'] * (10 / 3)))
        elimination_data['detectable'] = uses_dt + datetime.timedelta(days=10)

    else:
        # chronic heavy use: detectable for standard half-life * 10, _or_ 30 days
        elimination_data['full'] = uses_dt + datetime.timedelta(
            hours=(elimination_data['full'] * 10))
        elimination_data['detectable'] = uses_dt + datetime.timedelta(days=30)

    return elimination_data
コード例 #25
0
def sv_detail(request, topic_id):
    topic_info = {}
    topic_info['primary'] = SpecificViewHelpTopic.objects.get(id=topic_id)
    topic_info['supporting'] = SpecificViewTopicDetail.objects.filter(topic=topic_id)

    return render(request, 'dox/sv_detail.html', MiscMethods.add_header_info(topic_info))
コード例 #26
0
ファイル: views.py プロジェクト: dgets/lasttime
def extrapolate_halflife_data(request, sub_id):
    """
    This method has a little more beef to it than most.  First it determines
    whether or not the substance passed is lipid soluble or not.  If it is,
    then it tries to determine whether or not it's talking about THC.  If so,
    it utilizes an algorithm based on the Mayo Clinic labs' standards for the
    detectability of THC in urine to determine the detectable half-life
    duration.  If the substance is lipid soluble but not THC, we return an
    error message due to not having enough specific data to work with that
    just yet.  If it's only water/plasma soluble, we calculate solely the
    standard elimination projection (which is done for THC, as well), which is
    based on the 5.7 * half-life projection that I was quoted by one of my
    health care professionals.

    :param request:
    :param sub_id:
    :return:
    """

    # TODO: modularize the lipid_soluble weed block below
    substance = Substance.objects.get(id=sub_id)
    context = {}
    elimination_data = {
        'full':
        None,
        'detectable':
        None,
        'relevant_since':
        None,
        'last_usage':
        Usage.objects.filter(sub=sub_id,
                             user=request.user).order_by('-timestamp').first(),
        'uses':
        0
    }

    if substance.lipid_solubility and ('marijuana' in substance.common_name
                                       or 'weed' in substance.common_name):
        #process the information for the tweeds
        elimination_data = get_weed_stats(
            Usage.objects.filter(sub=sub_id,
                                 user=request.user).order_by('-timestamp'),
            substance.active_half_life)

    elif substance.lipid_solubility:
        # we can't process this yet
        context['error_message'] = \
            "We are not able to process half-life extrapolation for non-THC lipid soluble metabolites yet, sorry!"
    else:
        # last_usage = Usage.objects.filter(sub=sub_id, user=request.user).order_by('-timestamp').first()

        elimination_data['full'] = elimination_data['last_usage'].timestamp + \
                                   datetime.timedelta(hours=int(float(substance.half_life) * 5.7))
        elimination_data['detectable'] = elimination_data['full']

        # check if localization is needed
        if MiscMethods.is_localization_needed(elimination_data['full']):
            elimination_data['full'] = MiscMethods.localize_timestamp(
                elimination_data['full'])
        if MiscMethods.is_localization_needed(elimination_data['detectable']):
            elimination_data['detectable'] = MiscMethods.localize_timestamp(
                elimination_data['detectable'])
        if MiscMethods.is_localization_needed(
                elimination_data['last_usage'].timestamp):
            elimination_data['last_usage'] = MiscMethods.localize_timestamp(
                elimination_data['last_usage'].timestamp)

    context = {
        'sub': substance,
        'elimination_target': elimination_data['full'],
        'undetectable_target': elimination_data['detectable'],
        'last_usage': elimination_data['last_usage'].timestamp
    }

    return render(request, 'dataview/halflife.html',
                  MiscMethods.add_header_info(context))
コード例 #27
0
ファイル: views.py プロジェクト: dgets/lasttime
    def get_context_data(self, **kwargs):
        page_data = {}

        return MiscMethods.add_header_info(page_data)
コード例 #28
0
def edit(request, admin_id):
    """
    Provides the capability to edit an existing administration.

    :param request:
    :param admin_id:
    :return:
    """

    context = {
        'id': admin_id,
    }

    if request.method != "POST":
        # give 'em the form
        try:
            admin_details = Usage.objects.get(id=admin_id, user=request.user)
            context['admin_form'] = UsageForm(instance=admin_details)

        except Exception as ex:
            context[
                'error_message'] = "Invalid administration record request: " + str(
                    ex)
            # here we should really be throwing things back to the detail view,
            # but with an error message explaining what happened; waiting until
            # global error message handling is completed before doing this,
            # however

            return render(request, 'recadm/edit_admin.html',
                          MiscMethods.add_header_info(context))

        return render(request, 'recadm/edit_admin.html',
                      MiscMethods.add_header_info(context))

    new_admin_deets = Usage.objects.get(id=admin_id, user=request.user)
    new_admin_deets.sub = Substance.objects.get(id=request.POST['sub'])
    new_admin_deets.dosage = request.POST['dosage']
    new_admin_deets.timestamp = MiscMethods.str_to_datetime(
        request.POST['timestamp'])
    new_admin_deets.notes = request.POST['notes']

    # localize?
    if MiscMethods.is_localization_needed(new_admin_deets.timestamp):
        new_admin_deets.timestamp = MiscMethods.localize_timestamp(
            new_admin_deets.timestamp)

    try:
        new_admin_deets.save()
    except Exception as ex:
        context[
            'error_message'] = "Unable to save new administration details: " + str(
                ex)
        context['admin_form'] = UsageForm(instance=new_admin_deets)

        return render(request, 'recadm/edit_admin.html',
                      MiscMethods.add_header_info(context))

    # again, this is another one waiting for the global user/error message
    # displaying code, but in another area
    context['user_message'] = "Saved new administration details."
    context['admin_form'] = UsageForm(instance=new_admin_deets)

    # return render(request, 'recadm/edit_admin.html', MiscMethods.add_header_info(context))
    # so below here...  this really isn't the way to be doing this, with an absolute URL/path, but the other ways
    # weren't working, and this one was, so I took the easy out...  :P
    return redirect('/recadm/', context=MiscMethods.add_header_info(context))
コード例 #29
0
ファイル: views.py プロジェクト: dgets/lasttime
def class_data_summary(request, class_id):
    """
    View handles the summary data gathering and calculation for the
    class_details view to see all information regarding the usages within a
    particular class of substances.

    :param request:
    :param class_id:
    :return:
    """

    subs = Substance.objects.filter(sub_class=class_id)
    usages_list = []
    for sub in subs:
        usages_list.append(
            Usage.objects.filter(sub=sub.id,
                                 user=request.user).order_by("timestamp"))

    # now we process each sub in the usages_list for our stats
    sub_usage_stats = []
    sub_usage_stats_tuple = []
    sub_interval_stats = []
    cntr = 0
    interval_cntr = 0
    for usages in usages_list:
        if len(usages) < 2:
            interval_error = True
        else:
            interval_error = False

        sub_usage_stats.append(dataview_support.get_usage_stats(usages))
        if not interval_error:
            sub_interval_stats.append(
                dataview_support.get_interval_stats(usages))

        # now we'll stuff that data into our pre-existing data structure, at least until we've got time to rework
        # the template for what's here now
        if not interval_error:
            sub_usage_stats_tuple.append(
                (subs[cntr], usages_list[cntr], sub_usage_stats[cntr]['total'],
                 len(usages_list[cntr]), sub_usage_stats[cntr]['average'],
                 sub_usage_stats[cntr]['highest'],
                 sub_usage_stats[cntr]['lowest'],
                 sub_interval_stats[interval_cntr]))
            interval_cntr += 1
        else:
            sub_usage_stats_tuple.append(
                (subs[cntr], usages_list[cntr], sub_usage_stats[cntr]['total'],
                 len(usages_list[cntr]), sub_usage_stats[cntr]['average'],
                 sub_usage_stats[cntr]['highest'],
                 sub_usage_stats[cntr]['lowest'], False))

        cntr += 1

    # subs isn't really necessary here any more, but does simplify the template a bit
    context = {
        'subs': subs,
        'usages': sub_usage_stats_tuple,
    }

    return render(request, 'dataview/class_data_summary.html',
                  MiscMethods.add_header_info(context))
コード例 #30
0
ファイル: views.py プロジェクト: dgets/lasttime
    def get_context_data(self, **kwargs):
        usages = Usage.objects.filter(
            sub=self.kwargs['pk'],
            user=self.request.user).order_by("timestamp")
        # print("pk is: " + str(self.kwargs['pk']))

        # though it duplicates things, the following conditional just checks for errors that will screw up the graphing
        too_few_usages_error = False
        if len(usages) < 2:
            too_few_usages_error = True
        else:
            zero_interval_error = False
            prev_timestamp = None
            for use in usages:
                if prev_timestamp is not None and use.timestamp == prev_timestamp:
                    zero_interval_error = True

                prev_timestamp = use.timestamp

        if too_few_usages_error:
            return MiscMethods.add_header_info({
                'error_message':
                "Not enough usages to calculate statistics properly"
            })

        elif zero_interval_error:
            return MiscMethods.add_header_info({
                'error_message':
                "Zero intervals between datasets causing calculation errors"
            })

        else:
            # now we get to actually gathering/calculating stats
            # calculate usage statistics
            usage_data = dataview_support.get_usage_stats(usages)

            # timespan & average calculation
            span_data = dataview_support.get_interval_stats(usages)

            # having issues with this with <2 (or maybe it's <3) usages recorded; not stopping to fix it the right way
            # just yet here; next time work is done with this try to get to the bottom of it
            scale_factor = 1  # get_graph_normalization_divisor(span_data['longest'].total_seconds(), 600)

            return MiscMethods.add_header_info({
                'usages':
                usages,
                'usage_count':
                usage_data['count'],
                'usage_average':
                usage_data['average'],
                'usage_high':
                usage_data['highest'],
                'usage_low':
                usage_data['lowest'],
                'usage_total':
                usage_data['total'],
                'sub_dosage_units':
                usages[0].sub.units,
                'sub_name':
                Substance.objects.filter(pk=self.kwargs['pk'])[0].common_name,
                'sub_id':
                self.kwargs['pk'],
                'longest_span':
                span_data['longest'],
                'shortest_span':
                span_data['shortest'],
                'timespans':
                span_data['timespans'],
                'scale_factor':
                scale_factor,
                'average_span':
                span_data['average'],
            })