Debug School

rakesh kumar
rakesh kumar

Posted on

How to renders data in key-value pair from list in django

Pass the list to the template: In your Django view, pass the list containing the key-value pairs to the template context.

data should be there in list format

data = ['', '', 'Calories: 468', 'Total Fat: 24g', 'Saturated Fat: 9g', 'Cholesterol: 101mg', 'Sodium: 875mg', 'Total Carbohydrates: 19g', 'Dietary Fiber: 4g', 'Sugar: 5g', 'Protein: 40g']
Enter fullscreen mode Exit fullscreen mode

view.py file

modify the code to split the strings before passing them to the template:

def recipe_detail(request, id):           
    recipe = Recipe.objects.get(pk=id)
    field_value = recipe.nutrition    
    split_data = [item.split(':') if ':' in item else item for item in field_value]
    return render(request, 'openai/dashboard.html', {'nutrition': split_data}) 
Enter fullscreen mode Exit fullscreen mode

In template file

 {% if recipe %}

              <table>
                <thead>
                  <tr>
                    <h4 style="margin-top:10px">Nutrition value of {{ recipe.name }}:</h4>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <th style=" background-color: lightgray; border: 1px solid black; padding: 8px;">Nutrition</th>
                    <th style=" background-color: lightgray; border: 1px solid black; padding: 8px;">calories</th>
                  </tr>
                {% for item in nutrition %}
                {% if item %}
                  <tr>
                    {% if item|length > 1 %}
                      <td style=" border: 1px solid black;padding: 8px;"><strong>{{ item.0 }}</strong></td>
                      <td style=" border: 1px solid black;padding: 8px;">{{ item.1 }}</td>
                    {% else %}
                      <td  style=" border: 1px solid black;padding: 8px;"colspan="2">{{ item }}</td>
                    {% endif %}
                  </tr>
                {% endif %}
              {% endfor %}                 
                </tbody>
              </table>
              {% endif %}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)