Self hosted FLOSS fitness/workout, nutrition and weight tracker
Move custom exercise search function to API, update corresponding JS
Roland Geidera7381cd1f51d
diff --git a/wger/core/static/js/workout-manager.js b/wger/core/static/js/workout-manager.jsindex 737d62e7a..012a0ea83 100644--- a/wger/core/static/js/workout-manager.js+++ b/wger/core/static/js/workout-manager.js@@ -362,7 +362,7 @@ function init_remove_exercise_formset() {function init_edit_set() {// Initialise the autocompleter (our widget, defined above)$("#exercise-search").catcomplete({- source: '/' + get_current_language() + "/exercise/search/",+ source: '/api/v2/exercise/search/',minLength: 2,select: function (event, ui) {diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex 21f41c30b..c6f809ab6 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -16,18 +16,25 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.from rest_framework import viewsets-from rest_framework.decorators import linkfrom rest_framework.permissions import IsAuthenticatedOrReadOnlyfrom rest_framework.response import Response+from rest_framework.decorators import link+from rest_framework.decorators import api_view+from easy_thumbnails.alias import aliasesfrom easy_thumbnails.files import get_thumbnailer+from django.utils.translation import ugettext as _++from wger.config.models import LanguageConfig+from wger.exercises.models import Exercisefrom wger.exercises.models import Equipmentfrom wger.exercises.models import ExerciseCategoryfrom wger.exercises.models import ExerciseImagefrom wger.exercises.models import ExerciseCommentfrom wger.exercises.models import Muscle+from wger.utils.language import load_item_languagesfrom wger.utils.permissions import CreateOnly@@ -56,6 +63,47 @@ class ExerciseViewSet(viewsets.ModelViewSet):obj.license_author = self.request.user.username+@api_view(['GET'])+def search(request):+ '''+ Searches for exercises.++ This format is currently used by the exercise search autocompleter+ '''+ q = request.GET.get('term', None)+ results = []+ if not q:+ return Response(results)++ languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)+ exercises = (Exercise.objects.filter(name__icontains=q)+ .filter(language__in=languages)+ .filter(status__in=Exercise.EXERCISE_STATUS_OK)+ .order_by('category__name', 'name')+ .distinct())++ for exercise in exercises:+ if exercise.exerciseimage_set.exists():+ image_obj = exercise.exerciseimage_set.filter(is_main=True)[0]+ image = image_obj.image.url+ t = get_thumbnailer(image_obj.image)+ thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url+ else:+ image = None+ thumbnail = None++ exercise_json = {'id': exercise.id,+ 'name': exercise.name,+ 'value': exercise.name,+ 'category': _(exercise.category.name),+ 'image': image,+ 'image_thumbnail': thumbnail}++ results.append(exercise_json)++ return Response(results)++class EquipmentViewSet(viewsets.ReadOnlyModelViewSet):'''API endpoint for equipment objectsdiff --git a/wger/exercises/templates/exercise/overview.html b/wger/exercises/templates/exercise/overview.htmlindex c17b3ebc1..8c92b355c 100644--- a/wger/exercises/templates/exercise/overview.html+++ b/wger/exercises/templates/exercise/overview.html@@ -40,7 +40,7 @@ $(document).ready(function() {// Init the autocompleter$("#exercise-search").catcomplete({- source: "{% url 'wger.exercises.views.exercises.search' %}",+ source: "/api/v2/exercise/search/",minLength: 2,select: function(event, ui) {@@ -195,14 +195,14 @@ $(document).ready(function() {<h3>{% trans "Search" %}</h3><div class="ui-widget">- <form action="{% url 'wger.exercises.views.exercises.search' %}"+ <form action="/api/v2/exercise/search/"method="get"id="exercise_search_form">{% csrf_token %}<input name="term"type="search"id="exercise-search"- class="ajax-form-element"+ class="ajax-form-element form-control"placeholder="{% trans 'exercise name' %}"style="width:100%;"></form>diff --git a/wger/exercises/tests/test_exercise.py b/wger/exercises/tests/test_exercise.pyindex 37051f117..84c7b9ba6 100644--- a/wger/exercises/tests/test_exercise.py+++ b/wger/exercises/tests/test_exercise.py@@ -330,7 +330,7 @@ class ExercisesTestCase(WorkoutManagerTestCase):'''# 1 hit, "Very cool exercise"- response = self.client.get(reverse('wger.exercises.views.exercises.search'),+ response = self.client.get('/api/v2/exercise/search/',{'term': 'cool'})self.assertEqual(response.status_code, 200)result = json.loads(response.content)@@ -342,7 +342,7 @@ class ExercisesTestCase(WorkoutManagerTestCase):self.assertEqual(result[0]['image_thumbnail'], None)# 0 hits, "Pending exercise"- response = self.client.get(reverse('wger.exercises.views.exercises.search'),+ response = self.client.get('/api/v2/exercise/search/',{'term': 'Pending'})self.assertEqual(response.status_code, 200)result = json.loads(response.content)diff --git a/wger/exercises/urls.py b/wger/exercises/urls.pyindex bef0e7124..caea16f9c 100644--- a/wger/exercises/urls.py+++ b/wger/exercises/urls.py@@ -32,8 +32,6 @@ urlpatterns = patterns('wger.exercises.views',exercises.ExerciseListView.as_view(),name='exercise-overview'),- url(r'^search/$',- exercises.search),url(r'^(?P<id>\d+)/view/$',exercises.view,name='exercise-view'),diff --git a/wger/exercises/views/exercises.py b/wger/exercises/views/exercises.pyindex bdcc40c76..f92bc7f07 100644--- a/wger/exercises/views/exercises.py+++ b/wger/exercises/views/exercises.py@@ -14,12 +14,10 @@## You should have received a copy of the GNU Affero General Public Licenseimport logging-import jsonimport uuidfrom django.shortcuts import renderfrom django.shortcuts import get_object_or_404-from django.http import HttpResponsefrom django.http import HttpResponseRedirectfrom django.http import HttpResponseForbiddenfrom django.forms import ModelForm@@ -37,8 +35,6 @@ from django.views.generic import ListViewfrom django.views.generic import DeleteViewfrom django.views.generic import CreateViewfrom django.views.generic import UpdateView-from easy_thumbnails.files import get_thumbnailer-from easy_thumbnails.alias import aliasesfrom wger.manager.models import WorkoutLogfrom wger.exercises.models import Exercise, Muscle@@ -310,44 +306,3 @@ def decline(request, pk):exercise.save()messages.success(request, _('Exercise was successfully marked as rejected'))return HttpResponseRedirect(exercise.get_absolute_url())---def search(request):- '''- Search an exercise, return the result as a JSON list- '''-- # Perform the search- q = request.GET.get('term', '')-- languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)- exercises = (Exercise.objects.filter(name__icontains=q)- .filter(language__in=languages)- .filter(status__in=Exercise.EXERCISE_STATUS_OK)- .order_by('category__name', 'name')- .distinct())-- results = []- for exercise in exercises:- if exercise.exerciseimage_set.exists():- image_obj = exercise.exerciseimage_set.filter(is_main=True)[0]- image = image_obj.image.url- t = get_thumbnailer(image_obj.image)- thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url- else:- image = None- thumbnail = None-- exercise_json = {}- exercise_json['id'] = exercise.id- exercise_json['name'] = exercise.name- exercise_json['value'] = exercise.name- exercise_json['category'] = _(exercise.category.name)- exercise_json['image'] = image- exercise_json['image_thumbnail'] = thumbnail-- results.append(exercise_json)- data = json.dumps(results)-- # Return the results to the client- return HttpResponse(data, content_type='application/json')diff --git a/wger/urls.py b/wger/urls.pyindex c0313d5d5..626fe7378 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -154,6 +154,9 @@ urlpatterns = urlpatterns + patterns('',name='robots'),url(r'^manifest\.webapp$', WebappManifestView.as_view(template_name="manifest.webapp")),url(r'^amazon-manifest\.webapp$', WebappManifestView.as_view(template_name="amazon-manifest.webapp")),++ # APIurl(r'^api/', include(v1_api.urls)),+ url(r'^api/v2/exercise/search/', exercises_api_views.search),url(r'api/v2/', include(router.urls)),)