0

I'm currently creating a python app using the django webframework, that allows users to query an external API to get information about food nutrition (e.g calories, fats). Currently, when the user inputs their food in a search bar on the webpage, the API is queried and displayed in the terminal. I'm trying to display the information on the webpage but am having trouble rendering the data.

form.py

class NutritionForm(forms.Form):
    food = forms.CharField(max_length=100000)

def search(self):
    # result = {}
    food = self.cleaned_data['food']

    headers = {
        'x-app-id': "ff0ccea8",
        'x-app-key': "605660a17994344157a78f518a111eda",
        'x-remote-user-id': "7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632",
        'Content-Type': "application/x-www-form-urlencoded",

    }

    url = 'https://trackapi.nutritionix.com/v2/natural/nutrients'
    body = {
        'query': food,
        'timezone': 'US/Eastern',
    }
    response = requests.request("POST", url, data=body, headers=headers)
    data = response.json()

    print ('food name: ', data['foods'][0]['food_name'])
    print ('food calories: ', data['foods'][0]['nf_calories'])
    print ('food protein: ', data['foods'][0]['nf_protein'])
    print ('food fats: ', data['foods'][0]['nf_total_fat'])

views.py

def nutritionix(request):
    search_result = {}
    if 'food' in request.POST:
        form = NutritionForm(request.POST)
        if form.is_valid():
            search_result = form.search()
    else:
        form = NutritionForm()
    return render(request, 'nutrition/nutrition.html', {'form': form, 'search_results': search_result})

This is my html page that I am using to try and display the information. However, when I run the search, the API is queried, displayed in the terminal but, doesn't show up on the webpage.

html

{% block content %}
  <h2>Nutritionix API</h2>

  <form action="" method="post">
      {% csrf_token %}
      {{ form.as_p }}
    <button type="submit">Search Food info</button>
  </form>

    {% block body %}
    <div class="container">
        <p>Food name:  {{ food }}</p>
    </div>
{% endblock %}


{% endblock %}

Its not printing onto webpage, am I doing this correctly?

1 Answer 1

1

The search() method doesn't appear to return anything. Change this to return the result:

def search(self):
    ...
    return data['foods'][0]

Then in your view, you can output the result like this:

<div class="container">
    <p>Food name:  {{ search_results.food_name }}</p>
    <p>Food calories:  {{ search_results.nf_calories }}</p>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.