Self hosted FLOSS fitness/workout, nutrition and weight tracker
Move custom ingredient search function to API, update corresponding JS
Roland Geider41149ca97cbd
diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.pyindex 2a4364e79..d3833f172 100644--- a/wger/nutrition/api/views.py+++ b/wger/nutrition/api/views.py@@ -16,7 +16,7 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.from rest_framework import viewsets-from rest_framework.decorators import link+from rest_framework.decorators import link, api_viewfrom rest_framework.response import Responsefrom wger.nutrition.api.serializers import NutritionPlanSerializer@@ -27,6 +27,7 @@ from wger.nutrition.models import MealItemfrom wger.nutrition.models import WeightUnitfrom wger.nutrition.models import IngredientWeightUnitfrom wger.nutrition.models import NutritionPlan+from wger.utils.language import load_ingredient_languagesfrom wger.utils.viewsets import WgerOwnerObjectModelViewSet@@ -54,6 +55,36 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):'license_author')+@api_view(['GET'])+def search(request):+ '''+ Searches for ingredients.++ This format is currently used by the ingredient search autocompleter+ '''+ q = request.GET.get('term', None)+ results = []+ if not q:+ return Response(results)++ languages = load_ingredient_languages(request)++ # Perform the search+ q = request.GET.get('term', '')+ ingredients = Ingredient.objects.filter(name__icontains=q,+ language__in=languages,+ status__in=Ingredient.INGREDIENT_STATUS_OK)++ results = []+ for ingredient in ingredients:+ ingredient_json = {'id': ingredient.id,+ 'name': ingredient.name,+ 'value': ingredient.name}+ results.append(ingredient_json)++ return Response(results)++class WeightUnitViewSet(viewsets.ReadOnlyModelViewSet):'''API endpoint for weight unit objectsdiff --git a/wger/nutrition/static/js/nutrition.js b/wger/nutrition/static/js/nutrition.jsindex dec39a7fd..6fc085bc4 100644--- a/wger/nutrition/static/js/nutrition.js+++ b/wger/nutrition/static/js/nutrition.js@@ -71,7 +71,7 @@ function init_ingredient_autocompleter(){// Init the autocompleter$("#id_ingredient_searchfield").autocomplete({- source: '/' + get_current_language() + "/nutrition/ingredient/search/",+ source: '/api/v2/ingredient/search/',minLength: 2,select: function(event, ui) {diff --git a/wger/nutrition/templates/ingredient/overview.html b/wger/nutrition/templates/ingredient/overview.htmlindex 12bed87b6..7638d7540 100644--- a/wger/nutrition/templates/ingredient/overview.html+++ b/wger/nutrition/templates/ingredient/overview.html@@ -72,7 +72,7 @@ $(document).ready(function() {<input name="term"type="search"id="ingredient-search"- class="ajax-form-element"+ class="ajax-form-element form-control"placeholder="{% trans 'ingredient name' %}"style="width:100%;"></form>diff --git a/wger/nutrition/templates/ingredient/search.html b/wger/nutrition/templates/ingredient/search.htmldeleted file mode 100644index 221b503fb..000000000--- a/wger/nutrition/templates/ingredient/search.html+++ /dev/null@@ -1,36 +0,0 @@-{% extends "base.html" %}-{% load i18n %}--<!--- Title--->-{% block title %}{% trans "Search results" %}{% endblock %}---<!--- Main Content--->-{% block content %}--<h2>{% trans "Search results" %} - "{{ search_term }}"</h2>--<form action="{% url 'wger.nutrition.views.ingredient.search' %}"- method="get"- id="ingredient_search_form">- {% csrf_token %}- <input name="term" id="ingredient-search">-</form>--<ul>-{% for ingredient in ingredients %}- <li><a href="{% url 'ingredient-view' ingredient.id %}">{{ ingredient.name }}</a></li>-{% endfor %}-</ul>--{% endblock %}---<!--- Side bar--->-{% block sidebar %}{% endblock %}diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.pyindex addf2b9bf..aac22af79 100644--- a/wger/nutrition/tests/test_ingredient.py+++ b/wger/nutrition/tests/test_ingredient.py@@ -169,20 +169,6 @@ class IngredientSearchTestCase(WorkoutManagerTestCase):Helper function'''- # Perform the search- response = self.client.get(reverse('ingredient-search'), {'term': 'test'})- self.assertEqual(response.status_code, 200)- self.assertEqual(len(response.context['ingredients']), 2)- self.assertEqual(response.context['ingredients'][0].name,- 'Ingredient, test, 2, organic, raw')- self.assertEqual(response.context['ingredients'][1].name, 'Test ingredient 1')-- # Search for an ingredient pending review (0 hits, "Pending ingredient")- response = self.client.get(reverse('ingredient-search'), {'term': 'Pending'})- self.assertEqual(response.status_code, 200)- self.assertEqual(len(response.context['ingredients']), 0)-- # AJAX-Searchkwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}response = self.client.get(reverse('ingredient-search'), {'term': 'test'}, **kwargs)self.assertEqual(response.status_code, 200)@@ -191,7 +177,7 @@ class IngredientSearchTestCase(WorkoutManagerTestCase):self.assertEqual(result[0]['value'], 'Ingredient, test, 2, organic, raw')self.assertEqual(result[1]['value'], 'Test ingredient 1')- # AJAX Search for an ingredient pending review (0 hits, "Pending ingredient")+ # Search for an ingredient pending review (0 hits, "Pending ingredient")response = self.client.get(reverse('ingredient-search'), {'term': 'Pending'}, **kwargs)self.assertEqual(response.status_code, 200)result = json.loads(response.content)diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex 24dbbaa4a..cef1e7a46 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -96,9 +96,6 @@ urlpatterns = patterns('wger.nutrition.views',url(r'^ingredient/(?P<id>\d+)/view/(?P<slug>[-\w]+)/$',ingredient.view,name='ingredient-view'),- url(r'^ingredient/search/$',- ingredient.search,- name='ingredient-search'),url(r'^ingredient/(?P<pk>\d+)/get-units$',ingredient.ajax_get_ingredient_units,name='ingredient-get-units'),diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.pyindex 9f2e857ca..be0a7d488 100644--- a/wger/nutrition/views/ingredient.py+++ b/wger/nutrition/views/ingredient.py@@ -223,46 +223,6 @@ def decline(request, pk):return HttpResponseRedirect(ingredient.get_absolute_url())-def search(request):- '''- Search for an exercise, return the result as a JSON list or as HTML page, depending on how- the function was invoked- '''-- # Filter the ingredients the user will see by its language- # (the user can also want to see ingredients in English, see load_ingredient_languages)- languages = load_ingredient_languages(request)-- # Perform the search- q = request.GET.get('term', '')- ingredients = Ingredient.objects.filter(name__icontains=q,- language__in=languages,- status__in=Ingredient.INGREDIENT_STATUS_OK)-- # AJAX-request, this comes from the autocompleter. Create a list and send it back as JSON- if request.is_ajax():-- results = []- for ingredient in ingredients:- ingredient_json = {}- ingredient_json['id'] = ingredient.id- ingredient_json['name'] = ingredient.name- ingredient_json['value'] = ingredient.name- results.append(ingredient_json)- data = json.dumps(results)-- # Return the results to the server- return HttpResponse(data, content_type='application/json')-- # Usual search (perhaps JS disabled), present the results as normal HTML page- else:- template_data = {}- template_data.update(csrf(request))- template_data['ingredients'] = ingredients- template_data['search_term'] = q- return render(request, 'ingredient/search.html', template_data)--@login_requireddef ajax_get_ingredient_units(request, pk):'''diff --git a/wger/urls.py b/wger/urls.pyindex 626fe7378..9292e784a 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -106,7 +106,7 @@ router.register(r'exercisecomment', exercises_api_views.ExerciseCommentViewSet)router.register(r'muscle', exercises_api_views.MuscleViewSet)# Nutrition app-router.register(r'ingredient', nutrition_api_views.IngredientViewSet, base_name='api')+router.register(r'ingredient', nutrition_api_views.IngredientViewSet, base_name='api-ingredient')router.register(r'weightunit', nutrition_api_views.WeightUnitViewSet)router.register(r'ingredientweightunit', nutrition_api_views.IngredientWeightUnitViewSet)router.register(r'nutritionplan', nutrition_api_views.NutritionPlanViewSet)@@ -158,5 +158,8 @@ urlpatterns = urlpatterns + patterns('',# APIurl(r'^api/', include(v1_api.urls)),url(r'^api/v2/exercise/search/', exercises_api_views.search),+ url(r'^api/v2/ingredient/search/',+ nutrition_api_views.search,+ name='ingredient-search'),url(r'api/v2/', include(router.urls)),)