def view(request): ''' The BMI calculator detail page ''' context = {} form_data = {'height': request.user.userprofile.height, 'weight': request.user.userprofile.weight} context['form'] = BmiForm(initial=form_data) return render(request, 'bmi/form.html', context)
def calculate(request): ''' Calculates the BMI ''' data = [] form = BmiForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() # Create a new weight entry as needed request.user.userprofile.user_bodyweight(form.cleaned_data['weight']) bmi = request.user.userprofile.calculate_bmi() result = {'bmi': '{0:.2f}'.format(bmi), 'weight': form.cleaned_data['weight'], 'height': request.user.userprofile.height} data = json.dumps(result, cls=helpers.DecimalJsonEncoder) # Return the results to the client return HttpResponse(data, 'application/json')
def calculate(request): ''' Calculates the BMI ''' data = [] form = BmiForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() # Create a new weight entry as needed if (not WeightEntry.objects.filter(user=request.user).exists() or (datetime.date.today() - WeightEntry.objects.filter(user=request.user).latest().creation_date > datetime.timedelta(1))): entry = WeightEntry() entry.weight = form.cleaned_data['weight'] entry.user = request.user entry.creation_date = datetime.date.today() entry.save() # Update the last entry else: entry = WeightEntry.objects.filter(user=request.user).latest() entry.weight = form.cleaned_data['weight'] entry.save() bmi = request.user.userprofile.calculate_bmi() result = {'bmi': '{0:.2f}'.format(bmi), 'weight': form.cleaned_data['weight'], 'height': request.user.userprofile.height} data = json.dumps(result, cls=helpers.DecimalJsonEncoder) # Return the results to the client return HttpResponse(data, 'application/json')