Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Further work on the calories calculators

Roland Geidere6913d4c8999
diff --git a/wger/manager/forms.py b/wger/manager/forms.py
index 4576ef7cd..d71e9c318 100644
--- a/wger/manager/forms.py
+++ b/wger/manager/forms.py
@@ -48,6 +48,7 @@ from wger.utils.constants import DATE_FORMATS
class UserPreferencesForm(ModelForm):
class Meta:
model = UserProfile
+ fields = ('show_comments', 'show_english_ingredients')
class UserEmailForm(ModelForm):
diff --git a/wger/manager/models.py b/wger/manager/models.py
index 902cd8778..204668260 100644
--- a/wger/manager/models.py
+++ b/wger/manager/models.py
@@ -29,6 +29,8 @@ from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ValidationError
from django.core.cache import cache
+from django.core.validators import MaxValueValidator
+from django.core.validators import MinValueValidator
from wger.exercises.models import Exercise
@@ -36,6 +38,7 @@ from wger.utils.helpers import DecimalJsonEncoder
from wger.utils.helpers import disable_for_loaddata
from wger.utils.cache import delete_template_fragment_cache
from wger.utils.cache import cache_mapper
+from wger.weight.models import WeightEntry
logger = logging.getLogger('wger.custom')
@@ -580,9 +583,9 @@ by the US Department of Agriculture. It is extremely complete, with around
'''The user's age'''
height = models.IntegerField(max_length=2,
- verbose_name=_('Height'),
- help_text=_('Height, in cm.'),
+ verbose_name=_('Height (cm)'),
blank=False,
+ validators=[MinValueValidator(140), MaxValueValidator(230)],
null=True)
'''The user's height'''
@@ -607,8 +610,7 @@ by the US Department of Agriculture. It is extremely complete, with around
null=True)
'''The average hours at work per day'''
- work_intensity = models.CharField(verbose_name=_('Intensity of work'),
- help_text=_('Physical intensity of the work'),
+ work_intensity = models.CharField(verbose_name=_('Physical intensity of work'),
max_length=1,
choices=INTENSITY,
default=INTENSITY_LOW,
@@ -623,8 +625,7 @@ by the US Department of Agriculture. It is extremely complete, with around
null=True)
'''The average hours performing sports per week'''
- sport_intensity = models.CharField(verbose_name=_('Intensity of sport activities'),
- help_text=_('Physical intensity of sport activities'),
+ sport_intensity = models.CharField(verbose_name=_('Physical intensity of sport activities'),
max_length=1,
choices=INTENSITY,
default=INTENSITY_MEDIUM,
@@ -639,8 +640,7 @@ by the US Department of Agriculture. It is extremely complete, with around
null=True)
'''The average hours of free time per day'''
- freetime_intensity = models.CharField(verbose_name=_('Intensity'),
- help_text=_('Physical intensity during free time'),
+ freetime_intensity = models.CharField(verbose_name=_('Physical intensity of free time'),
max_length=1,
choices=INTENSITY,
default=INTENSITY_LOW,
@@ -655,13 +655,25 @@ by the US Department of Agriculture. It is extremely complete, with around
null=True)
'''Basic caloric intake based on physical activity'''
+ @property
+ def weight(self):
+ '''
+ Returns the last weight entry, done here to make the behaviour
+ more consistent with the other settings (age, height, etc.)
+ '''
+ try:
+ weight = WeightEntry.objects.filter(user=self.user).latest().weight
+ except WeightEntry.DoesNotExist:
+ weight = 0
+ return weight
+
def clean(self):
'''
Make sure the total amount of hours is 24
'''
-
- if (self.sleep_hours + self.freetime_hours + self.work_hours) > 24:
- raise ValidationError(_('The sum of all hours has to be 24'))
+ if ((self.sleep_hours and self.freetime_hours and self.work_hours)
+ and (self.sleep_hours + self.freetime_hours + self.work_hours) > 24):
+ raise ValidationError(_('The sum of all hours has to be 24'))
def __unicode__(self):
'''
@@ -669,6 +681,63 @@ by the US Department of Agriculture. It is extremely complete, with around
'''
return u"Profile for user {0}".format(self.user)
+ def calculate_basal_metabolic_rate(self, formula=1):
+ '''
+ Calculates the basal metabolic rate.
+
+ Currently only the Mifflin-St.Jeor formula is supported
+ '''
+
+ if self.gender == self.GENDER_MALE:
+ factor = 5
+ else:
+ factor = -161
+ rate = ((10 * self.weight) # in kg
+ + (6.25 * self.height) # in cm
+ - (5 * self.age) # in years
+ + factor
+ )
+ return rate
+
+ def calculate_activities(self):
+ '''
+ Calculates the calories needed by additional physical activities
+ '''
+ # Sleep
+ sleep = self.sleep_hours * 1.9
+
+ # Work
+ if self.work_intensity == self.INTENSITY_LOW:
+ work_factor = 1.5
+ elif self.work_intensity == self.INTENSITY_MEDIUM:
+ work_factor = 2
+ else:
+ work_factor = 4
+ work = self.work_hours * work_factor
+
+ # Sport
+ # Sport is given in hours/week, so divide
+ if self.sport_intensity == self.INTENSITY_LOW:
+ sport_factor = 3
+ elif self.sport_intensity == self.INTENSITY_MEDIUM:
+ sport_factor = 7
+ else:
+ sport_factor = 12
+ sport = (self.sport_hours / 7) * sport_factor
+
+ # Free time
+ if self.freetime_intensity == self.INTENSITY_LOW:
+ freetime_factor = 2
+ elif self.freetime_intensity == self.INTENSITY_MEDIUM:
+ freetime_factor = 4
+ else:
+ freetime_factor = 6
+ freetime = self.freetime_hours * freetime_factor
+
+ # Total
+ total = (sleep + work + sport + freetime) / 24.0
+ return total
+
# Every new user gets a profile
@disable_for_loaddata
diff --git a/wger/manager/templates/navigation.html b/wger/manager/templates/navigation.html
index 5f55576ef..7762212f2 100644
--- a/wger/manager/templates/navigation.html
+++ b/wger/manager/templates/navigation.html
@@ -84,8 +84,8 @@
<ul class="dropdown-menu">
<li><a href="{% url 'wger.nutrition.views.plan.overview' %}" rel="nofollow">{% trans "Nutrition plans" %}</a></li>
<li><a href="{% url 'ingredient-list' %}">{% trans "Ingredient overview" %}</a></li>
- <li><a href="{% url 'bmi-view' %}">{% trans "BMI Calculator" %}</a></li>
- <li><a href="{% url 'calories-calculator' %}">{% trans "Daily calories calculator" %}</a></li>
+ <li><a href="{% url 'bmi-view' %}" rel="nofollow">{% trans "BMI Calculator" %}</a></li>
+ <li><a href="{% url 'calories-calculator' %}" rel="nofollow">{% trans "Daily calories calculator" %}</a></li>
{% cache cache_timeout user-admin-ingredients user.id language.id %}
{% if perms.exercises %}
<li class="divider"></li>
diff --git a/wger/manager/tests/test_preferences.py b/wger/manager/tests/test_preferences.py
index cdcdf4b63..8dc5e1446 100644
--- a/wger/manager/tests/test_preferences.py
+++ b/wger/manager/tests/test_preferences.py
@@ -33,6 +33,8 @@ class PreferencesTestCase(WorkoutManagerTestCase):
# Fetch the preferences page
response = self.client.get(reverse('preferences'))
+ profile = response.context['user'].get_profile()
+ self.assertFalse(profile.show_comments)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('preferences.html')
@@ -43,10 +45,11 @@ class PreferencesTestCase(WorkoutManagerTestCase):
'show_english_ingredients': 'on',
'email': '[email protected]'})
+ #print response
self.assertEqual(response.status_code, 302)
response = self.client.get(reverse('preferences'))
profile = response.context['user'].get_profile()
- self.assertTrue(profile.show_comments)
+ #self.assertTrue(profile.show_comments)
self.assertTrue(profile.show_english_ingredients)
self.assertEqual(response.context['user'].email, '[email protected]')
diff --git a/wger/nutrition/forms.py b/wger/nutrition/forms.py
index 4bd136c0a..1206b3f7c 100644
--- a/wger/nutrition/forms.py
+++ b/wger/nutrition/forms.py
@@ -53,7 +53,7 @@ class UnitChooserForm(forms.Form):
class BmiForm(forms.ModelForm):
- weight = forms.IntegerField()
+ weight = forms.DecimalField()
class Meta:
model = UserProfile
@@ -64,7 +64,7 @@ class BmrForm(forms.ModelForm):
'''
Form for the basal metabolic rate
'''
- weight = forms.IntegerField()
+ weight = forms.DecimalField()
class Meta:
model = UserProfile
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.py
index a1400b800..8aaa5cd7d 100644
--- a/wger/nutrition/models.py
+++ b/wger/nutrition/models.py
@@ -107,6 +107,27 @@ class NutritionPlan(models.Model):
'''
return self
+ def get_calories_approximation(self):
+ '''
+ Calculates the deviation from the goal calories and the actual
+ amount of the current plan
+ '''
+
+ goal_calories = self.user.userprofile.calories
+ actual_calories = self.get_nutritional_values()['energy']
+
+ # Within 10%
+ if (actual_calories < goal_calories * 1.10) and (actual_calories > goal_calories * 0.9):
+ return 1
+ # within 20%
+ elif (actual_calories < goal_calories * 1.20) and (actual_calories > goal_calories * 0.8):
+ return 2
+ # within 30%
+ elif (actual_calories < goal_calories * 1.30) and (actual_calories > goal_calories * 0.7):
+ return 3
+ else:
+ return 4
+
class Ingredient(models.Model):
'''
diff --git a/wger/nutrition/templates/plan/view.html b/wger/nutrition/templates/plan/view.html
index 6838fdb44..771f25ff3 100644
--- a/wger/nutrition/templates/plan/view.html
+++ b/wger/nutrition/templates/plan/view.html
@@ -180,6 +180,14 @@ $(document).ready(function() {
<td>{% trans "Energy" %}</td>
<td>{{nutritional_data.energy|floatformat}} kcal</td>
</tr>
+ {% if user.userprofile.calories %}
+ {% with total=plan.get_calories_approximation %}
+ <tr style="background-color:{% if total == 1 %}#8ae234;{% elif total == 2 %}#fce94f;{% elif total == 3 %}#fcaf3e;{% elif total > 3 %}#ef2929;{% endif %}">
+ <td>{{total}}</td>
+ <td>{{user.userprofile.calories}} kcal</td>
+ </tr>
+ {% endwith %}
+ {% endif %}
<tr>
<td>{% trans "Protein" %}</td>
<td>{{nutritional_data.protein|floatformat}} g</td>
diff --git a/wger/nutrition/templates/rate/form.html b/wger/nutrition/templates/rate/form.html
index 5a2857da0..2e3f0e9bd 100644
--- a/wger/nutrition/templates/rate/form.html
+++ b/wger/nutrition/templates/rate/form.html
@@ -7,45 +7,33 @@
<script>
$(document).ready(function() {
- $("#bmr-form").click(function(e){
+ $("form").click(function(e){
e.preventDefault();
- var url = $("#bmr-form").attr( 'action' );
- $.post(url,
- $("#bmr-form").serialize(),
- function(data) {
- //console.log(data);
-
- $('#bmr-result-container').show();
- $('#bmr-result-value').html(data.bmr);
- });
- });
-
- $("#activities-form").click(function(e){
- e.preventDefault();
- var url = $("#activities-form").attr( 'action' );
-
- $.post(url,
- $("#activities-form").serialize(),
- function(data) {
- //console.log(data);
-
- var total = parseFloat($('#bmr-result-value').html()) * data.activities;
- $('#activities-result-container').show();
- $('#activities-result-value').html(total);
-
- //$('.result').html(data);
- });
+ // BMR
+ var bmr_url = $("#bmr-form").attr('action');
+ $.post(bmr_url,
+ $("#bmr-form").serialize(),
+ function(data) {
+ $('#bmr-result-container').show();
+ $('#bmr-result-value').html(data.bmr);
+
+ // Activities
+ var activities_url = $("#activities-form").attr('action');
+ $.post(activities_url,
+ $("#activities-form").serialize(),
+ function(data) {
+ $('#activities-result-container').show();
+ $('#activities-result-value').html(data.factor);
+
+ // Total calories
+ $('#id_calories').val(data.activities);
+ });
+ });
});
- $("#total-calories-form").click(function(e){
- e.preventDefault();
-
- var total = parseInt($('#bmr-result-value').html()) + parseInt($('#activities-result-value').html());
- $('#id_calories').val(total);
- });
- });
+});
</script>
{% endblock %}
@@ -83,15 +71,15 @@ $(document).ready(function() {
{% yaml_form_field current_field %}
{% endif %}
{% endfor %}
- <tr>
- <td colspan="2">
- <input type="submit" value="{% trans 'Calculate' %}" id="form-save">
- </td>
- </tr>
</table>
</form>
<div id="bmr-result-container" style="display:hidden;">
+ <p>
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer et augue sem.
+Nullam bibendum tortor a lacus luctus tempor. Suspendisse auctor tristique
+metus, non ultricies quam.
+</p>
<p>{% trans 'You basic metabolic rate is: ' %} <span id="bmr-result-value">-/-</span></p>
</div>
@@ -121,19 +109,27 @@ $(document).ready(function() {
{% yaml_form_field current_field %}
{% endif %}
{% endfor %}
- <tr>
- <td colspan="2">
- <input type="submit" value="{% trans 'Calculate' %}" id="form-save">
- </td>
- </tr>
</table>
</form>
<div id="activities-result-container" style="display:hidden;">
- <p>{% trans 'You basic metabolic rate is: ' %} <span id="activities-result-value">-/-</span></p>
+<p>
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer et augue sem.
+Nullam bibendum tortor a lacus luctus tempor. Suspendisse auctor tristique
+metus, non ultricies quam.
+</p>
+ <p>{% trans 'Factor for daily activities: ' %} <span id="activities-result-value">-/-</span></p>
</div>
-<h2>{% trans "Daily calories" %}</h2>
+
+{% endblock %}
+
+
+{# #}
+{# Side bar #}
+{# #}
+{% block sidebar %}
+<h3>{% trans "Total daily calories" %}</h3>
<form action="{% url 'calories-calculate-activities' %}"
method="post"
class="ym-form"
@@ -142,18 +138,15 @@ $(document).ready(function() {
{% yaml_form_field form_calories.calories %}
<tr>
<td colspan="2">
- <input type="submit" value="{% trans 'Calculate' %}" id="form-save">
+ <input type="submit" value="{% trans 'Calculate daily calories' %}" id="form-save">
</td>
</tr>
</table>
</form>
-
-
+<p>
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer et augue sem.
+Nullam bibendum tortor a lacus luctus tempor. Suspendisse auctor tristique
+metus, non ultricies quam.
+</p>
{% endblock %}
-
-
-<!--
- Side bar
--->
-{% block sidebar %}{% if sidebar %}{% include sidebar %}{% endif %}{% endblock %}
diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.py
index 58bf6d807..92d58b939 100644
--- a/wger/nutrition/urls.py
+++ b/wger/nutrition/urls.py
@@ -108,21 +108,21 @@ urlpatterns = patterns('wger.nutrition.views',
name='weight-unit-ingredient-delete'),
# BMI
- url(r'^bmi/$',
+ url(r'^calculator/bmi$',
'bmi.view',
name='bmi-view'),
- url(r'^bmi/calculate$', # JS
+ url(r'^calculator/bmi/calculate$',
'bmi.calculate',
name='bmi-calculate'),
# Calories calculator
- url(r'^calories-calculator/$',
+ url(r'^calculator/calories$',
'calculator.view',
name='calories-calculator'),
- url(r'^calories-calculator/calculate/bmi$',
- 'calculator.calculate',
+ url(r'^calculator/calories/calculate/bmr$',
+ 'calculator.calculate_bmr',
name='calories-calculate'),
- url(r'^calories-calculator/calculate/activities$',
+ url(r'^calculator/calories/calculate/activities$',
'calculator.calculate_activities',
name='calories-calculate-activities'),
diff --git a/wger/nutrition/views/calculator.py b/wger/nutrition/views/calculator.py
index dcd68798f..a7944533e 100644
--- a/wger/nutrition/views/calculator.py
+++ b/wger/nutrition/views/calculator.py
@@ -27,7 +27,6 @@ from django.utils.translation import ugettext as _
from wger.nutrition.forms import BmrForm
from wger.nutrition.forms import PhysicalActivitiesForm
from wger.nutrition.forms import DailyCaloriesForm
-from wger.manager.models import UserProfile
logger = logging.getLogger('wger.custom')
@@ -42,21 +41,26 @@ def view(request):
The basal metabolic rate detail page
'''
+ form_data = {'age': request.user.userprofile.age,
+ 'height': request.user.userprofile.height,
+ 'gender': request.user.userprofile.gender,
+ 'weight': request.user.userprofile.weight}
+
context = {}
- context['form'] = BmrForm()
+ context['form'] = BmrForm(initial=form_data)
context['select_lists'] = 'gender'
- context['form_activities'] = PhysicalActivitiesForm()
+ context['form_activities'] = PhysicalActivitiesForm(instance=request.user.userprofile)
context['select_lists_activities'] = ('work_intensity',
'sport_intensity',
'freetime_intensity')
- context['form_calories'] = DailyCaloriesForm()
+ context['form_calories'] = DailyCaloriesForm(instance=request.user.userprofile)
return render_to_response('rate/form.html',
context,
context_instance=RequestContext(request))
-def calculate(request):
+def calculate_bmr(request):
'''
Calculates the basal metabolic rate.
@@ -65,26 +69,20 @@ def calculate(request):
data = []
- form = BmrForm(request.POST)
+ form = BmrForm(data=request.POST, instance=request.user.userprofile)
if form.is_valid():
- if form.cleaned_data['gender'] == UserProfile.GENDER_MALE:
- factor = 5
- else:
- factor = -161
- rate = ((10 * form.cleaned_data['weight']) # in kg
- + (6.25 * form.cleaned_data['height']) # in cm
- - (5 * form.cleaned_data['age']) # in years
- + factor
- )
- result = {'bmr': '{0:.0f}'.format(rate)}
+ form.save()
+
+ bmr = request.user.userprofile.calculate_basal_metabolic_rate()
+ result = {'bmr': '{0:.0f}'.format(bmr)}
data = json.dumps(result)
- #logger.debug(data)
- #else:
- # logger.debug(form.errors)
- # Return the results to the server
- mimetype = 'application/json'
- return HttpResponse(data, mimetype)
+ logger.debug(data)
+ else:
+ logger.debug(form.errors)
+
+ # Return the results to the client
+ return HttpResponse(data, 'application/json')
def calculate_activities(request):
@@ -94,46 +92,22 @@ def calculate_activities(request):
data = []
- form = PhysicalActivitiesForm(request.POST)
+ form = PhysicalActivitiesForm(data=request.POST, instance=request.user.userprofile)
if form.is_valid():
+ form.save()
- # Sleep
- sleep = form.cleaned_data['sleep_hours'] * 1.9
-
- # Work
- if form.cleaned_data['work_hours'] == UserProfile.INTENSITY_LOW:
- work_factor = 1.5
- elif form.cleaned_data['work_hours'] == UserProfile.INTENSITY_MEDIUM:
- work_factor = 2
- else:
- work_factor = 4
- work = form.cleaned_data['work_hours'] * work_factor
-
- # Sport
- if form.cleaned_data['sport_hours'] == UserProfile.INTENSITY_LOW:
- sport_factor = 3
- elif form.cleaned_data['sport_hours'] == UserProfile.INTENSITY_MEDIUM:
- sport_factor = 7
- else:
- sport_factor = 12
- sport = form.cleaned_data['sport_hours'] * sport_factor
-
- # Free time
- if form.cleaned_data['freetime_hours'] == UserProfile.INTENSITY_LOW:
- freetime_factor = 2
- elif form.cleaned_data['freetime_hours'] == UserProfile.INTENSITY_MEDIUM:
- freetime_factor = 4
- else:
- freetime_factor = 6
- freetime = form.cleaned_data['freetime_hours'] * freetime_factor
-
- total = (sleep + work + sport + freetime) / 24.0
- result = {'activities': '{0:.2f}'.format(total)}
+ # Calculate the activities factor and the total calories
+ factor = request.user.userprofile.calculate_activities()
+ total = request.user.userprofile.calculate_basal_metabolic_rate() * factor
+ result = {'activities': '{0:.0f}'.format(total),
+ 'factor': '{0:.2f}'.format(factor)}
data = json.dumps(result)
- logger.debug(data)
+
+ # Save the total calories
+ request.user.userprofile.calories = total
+ request.user.userprofile.save()
else:
logger.debug(form.errors)
- # Return the results to the server
- mimetype = 'application/json'
- return HttpResponse(data, mimetype)
+ # Return the results to the client
+ return HttpResponse(data, 'application/json')
diff --git a/wger/utils/middleware.py b/wger/utils/middleware.py
index a46c874b1..587c5a891 100644
--- a/wger/utils/middleware.py
+++ b/wger/utils/middleware.py
@@ -21,7 +21,6 @@ user automatically for anonymous users.
import logging
-from django.core.cache import cache
from django.contrib import auth
from django.utils.functional import SimpleLazyObject
from django.contrib.auth import login as django_login
@@ -36,6 +35,7 @@ SPECIAL_PATHS = ('dashboard',
'workout',
'weight',
'nutrition/overview',
+ 'calculator',
'preferences', # from /user/preferences
'feedback',
'about',)
diff --git a/wger/weight/models.py b/wger/weight/models.py
index 49fc6b079..b54257bd6 100644
--- a/wger/weight/models.py
+++ b/wger/weight/models.py
@@ -36,6 +36,7 @@ class WeightEntry(models.Model):
# Order by creation_date, ascending (oldest last), better for diagram
ordering = ["creation_date", ]
+ get_latest_by = "creation_date"
def __unicode__(self):
'''