Self hosted FLOSS fitness/workout, nutrition and weight tracker
Make the CSV import for weight entries more user friendly
Roland Geider176544d9da9c
diff --git a/weight/helpers.py b/weight/helpers.pynew file mode 100644index 000000000..03cf6e545--- /dev/null+++ b/weight/helpers.py@@ -0,0 +1,53 @@+# -*- coding: utf-8 -*-++# This file is part of Workout Manager.+#+# Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++import logging+import StringIO+import datetime+import decimal+import csv++from weight.models import WeightEntry++logger = logging.getLogger('workout_manager.custom')+++def parse_weight_csv(request, cleaned_data):++ try:+ dialect = csv.Sniffer().sniff(cleaned_data['csv_input'])+ except csv.Error:+ logger.debug('Error while sniffing CSV format')+ dialect='excel'++ # csv.reader expects a file-like object, so use StringIO+ parsed_csv = csv.reader(StringIO.StringIO(cleaned_data['csv_input']),+ dialect)++ weight_list = []+ error_list = []+ for row in parsed_csv:+ try:+ parsed_date = datetime.datetime.strptime(row[0], cleaned_data['date_format'])+ parsed_weight = decimal.Decimal(row[1].replace(',', '.'))+ weight_list.append(WeightEntry(creation_date=parsed_date,+ weight=parsed_weight,+ user=request.user))+ except (ValueError, decimal.InvalidOperation), e:+ error_list.append(row)+ logger.debug(e)++ return (weight_list, error_list)diff --git a/weight/templates/import_csv_form.html b/weight/templates/import_csv_form.htmlindex bc74c225f..73c239bef 100644--- a/weight/templates/import_csv_form.html+++ b/weight/templates/import_csv_form.html@@ -2,11 +2,10 @@{% load manager_extras %}{% load i18n %}-{% block title %}{% trans "Import CSV file" %}{% endblock %}+{% block title %}{% trans "Import weight logs" %}{% endblock %}{% block content %}-<h2>{% trans "Import CSV file" %}</h2>-+<h2>{% trans "Import weight logs" %}</h2><form action="{{form_action}}"method="post"@@ -16,7 +15,8 @@<input type="hidden" name="{{ stage_field }}" value="1" /><table>{% yaml_form_field form.csv_input %}- {% yaml_form_field form.separator "ym-fbox-select" %}+ {% yaml_form_field form.date_format "ym-fbox-select" %}+<tr><td colspan="2"><input type="submit" value="{% trans 'Submit' %}" id="form-save">@@ -24,6 +24,20 @@</tr></table></form>+{% endblock %}+++{% block sidebar %}+<p>{% blocktrans %}Use this import field to import your weight logs into Workout+Manager.{% endblocktrans %}</p>++<p>{% blocktrans %}You can copy and paste from your spreadsheet into the text input,+the system will try to guess the format to import. The only things to consider is+that the first column is the <strong>date</strong>, the second the <strong>weight</strong>.+All further columns are ignored.+{% endblocktrans %}</p>+<p>{% blocktrans %}If there are errors, you can correct or discard them in a+second step.{% endblocktrans %}</p>{% endblock %}diff --git a/weight/templates/import_csv_preview.html b/weight/templates/import_csv_preview.htmlindex 3fe3a3840..29e05887a 100644--- a/weight/templates/import_csv_preview.html+++ b/weight/templates/import_csv_preview.html@@ -2,42 +2,86 @@{% load manager_extras %}{% load i18n %}-{% block title %}{% trans "Preview imported CSV file" %}{% endblock %}+{% block title %}{% trans "Preview imported CSV entries" %}{% endblock %}{% block content %}-<h2>{% trans "Preview imported CSV file" %}</h2>+<h2>{% trans "Preview imported CSV entries" %}</h2>-{% for i in weight_list %}- {{i}}-{% endfor %}--<table>-{% for field in form %}+<h3>{% trans "Sucessfully converted values" %}</h3>+<div class="box success">{% trans "The following values could be converted." %}</div>+<table class="narrow"><tr>-<th>{{ field.label }}:</th>-<td>{{ field.data }}</td>+ <th>{% trans "Date" %}</th>+ <th>{% trans "Weight" %}</th></tr>+{% for entry in weight_list %}+ <tr>+ <td>{{ entry.creation_date|date:"SHORT_DATE_FORMAT" }}</td>+ <td>{{ entry.weight }}</td>+ </tr>{% endfor %}</table>-<p>Security hash: {{ hash_value }}</p>-<form action="" method="post">{% csrf_token %}-{% for field in form %}{{ field.as_hidden }}-{% endfor %}+<h3>{% trans "Errors" %}</h3>++{% if error_list %}+ <div class="box error">{% trans "The following values could not be converted." %}</div>++ <p>{% blocktrans %}These values could not be converted to a weight log entry.+ The reasons for this could be anything from an unrecognised date or number+ format, a problem with the encoding or something else. Please check that+ there are no obvious errors in the list (and correct them if there are!)+ and try to import the list again.{% endblocktrans %}</p>++ <p>{% blocktrans %}Remember that the expected structure is <strong>date</strong>+ on the first columns and <strong>weight</strong> on the second.{% endblocktrans %}</p>++ <table class="narrow">+ <tr>+ <th>{% trans "Date" %}</th>+ <th>{% trans "Weight" %}</th>+ </tr>+ {% for entry in error_list %}+ <tr>+ <td>{{ entry.0 }}</td>+ <td>{{ entry.1 }}</td>+ </tr>+ {% endfor %}+</table>++{% else %}+ <p>{% blocktrans %}There were no errors, all entries could be converted!{% endblocktrans %}</p>+{% endif %}+++<h2>{% trans "Import all successfully converted entries" %}</h2>+<p>{% blocktrans %}Continue here if you want to import into your weight log all+entries that were sucessfully converted. All entries that produced an error+will simply be ignored. It's up to you to decide whether they are useful+(unrecognised entries) or not (e.g. headers, comments, etc.).{% endblocktrans %}</p>++<form action="{{form_action}}"+ method="post"+ class="ym-form">+{% csrf_token %}+{% for field in form %}{{ field.as_hidden }}{% endfor %}+<input type="hidden" name="{{ stage_field }}" value="2" /><input type="hidden" name="{{ hash_field }}" value="{{ hash_value }}" />-<p><input type="submit" value="Submit" /></p>+<p><input type="submit" value="{% trans 'Import' %}" /></p></form>-<h2>Or edit it again</h2>+<h2>{% trans "Or try it again" %}</h2>+<p>{% blocktrans %}You can correct the list here and re-submit it as often as+you want.{% endblocktrans %}</p><form action="{{form_action}}"method="post"@@ -47,10 +91,10 @@<input type="hidden" name="{{ stage_field }}" value="1" /><table>{% yaml_form_field form.csv_input %}- {% yaml_form_field form.separator "ym-fbox-select" %}+ {% yaml_form_field form.date_format "ym-fbox-select" %}<tr><td colspan="2">- <input type="submit" value="{% trans 'Submit' %}" id="form-save">+ <input type="submit" value="{% trans 'Re-Submit' %}" id="form-save"></td></tr></table>diff --git a/weight/templates/weight_overview.html b/weight/templates/weight_overview.htmlindex 606c1d69e..f5b9e6039 100644--- a/weight/templates/weight_overview.html+++ b/weight/templates/weight_overview.html@@ -127,13 +127,12 @@ on the background resets it.</p><p>- <a href="{% url weight-import-csv %}"- target="_blank">+ <a href="{% url weight-import-csv %}"><img src="{% static 'images/icons/save.svg' %}"width="32"height="32"- alt="{% trans 'Export as CSV' %}"- title="{% trans 'Export as CSV' %}">+ alt="{% trans 'Import CSV' %}"+ title="{% trans 'Import CSV' %}">{% trans "Import CSV" %}</a></p>diff --git a/weight/views.py b/weight/views.pyindex 4742d3069..e06003a10 100644--- a/weight/views.py+++ b/weight/views.py@@ -17,8 +17,7 @@import loggingimport csvimport json-import StringIO-import datetime+from django.template import RequestContextfrom django.shortcuts import render_to_response@@ -43,6 +42,7 @@ from django.views.generic import CreateViewfrom django.views.generic import UpdateViewfrom weight.models import WeightEntry+from weight import helpersfrom workout_manager.generic_views import YamlFormMixinfrom workout_manager.constants import WEIGHT_TAB@@ -181,49 +181,32 @@ def get_weight_data(request):return HttpResponse(json.dumps(chart_data), mimetype)--CSV_SEPARATORS = ((';', 'semi colon (;)'),- ('\t', 'tabulator'))+CSV_DATE_FORMAT = (+ ('%d.%m.%Y', 'DD.MM.YYYY (30.01.2012)'),+ ('%d.%m.%y', 'DD.MM.YY (30.01.12)'),+ ('%Y-%m-%d', 'YYYY-MM-DD (2012-01-30)'),+ ('%y-%m-%d', 'YY-MM-DD (12-01-30)'),+ ('%m/%d/%Y', 'MM/DD/YYYY (01/30/2012)'),+ ('%m/%d/%y', 'MM/DD/YY (01/30/12)'),+ )class WeightCsvImportForm(Form):'''A helper form with only a textarea'''csv_input = CharField(widget=Textarea)- separator = forms.ChoiceField(choices=CSV_SEPARATORS)---def parse_weight_csv(request, cleaned_data):-- try:- dialect = csv.Sniffer().sniff(cleaned_data['csv_input'])- except csv.Error:- logger.debug('Error while sniffing CSV format')- dialect='excel'-- # csv.reader expects a file-like object, so use StringIO- parsed_csv = csv.reader(StringIO.StringIO(cleaned_data['csv_input']),- dialect)-- weight_list = []- for row in parsed_csv:- parsed_date = datetime.datetime.strptime(row[0], '%Y-%m-%d')- parsed_weight = int(row[1])- weight_list.append(WeightEntry(creation_date=parsed_date,- weight=parsed_weight,- user=request.user))- return weight_list--+ date_format = forms.ChoiceField(choices=CSV_DATE_FORMAT)++class WeightCsvImportFormPreview(FormPreview):preview_template = 'import_csv_preview.html'form_template = 'import_csv_form.html'-+def get_context(self, request, form):'''Context for template rendering.'''-+return {'form': form,'stage_field': self.unused_name('stage'),'state': self.state,@@ -231,11 +214,11 @@ class WeightCsvImportFormPreview(FormPreview):'form_action': reverse('weight-import-csv')}def process_preview(self, request, form, context):- context['weight_list'] = parse_weight_csv(request, form.cleaned_data)+ context['weight_list'], context['error_list'] = helpers.parse_weight_csv(request, form.cleaned_data)return context-+def done(self, request, cleaned_data):- weight_list = parse_weight_csv(request, cleaned_data)+ weight_list, error_list = helpers.parse_weight_csv(request, cleaned_data)WeightEntry.objects.bulk_create(weight_list)return HttpResponseRedirect(reverse('weight-overview'))-+