0

views.py

from django.shortcuts import render, redirect
import wikipedia
from wikipedia.exceptions import DisambiguationError, PageError

def index(request):
    context = {}
    if request.GET.get('search'):
        search_value = wikipedia.search(request.GET.get('search'), results=3)
        print(search_value)
        keys = search_value
        values = []
        for s in search_value:
            print(s)
            try:
                if wikipedia.summary(s):
                    values.append(wikipedia.summary(s))
            except DisambiguationError as error:
                print('errorrrrrr \n', error)
                values.append("Disambiguation error")
            except PageError as error:
                print('erorrrrrrr \n', error)
                values.append("Page error")
        for i in range(len(keys)):
            context[keys[i]] = values[i]
        context = dict(zip(keys, values))
    res = not bool(context)
    print(res)
    for key, value in context.items():
        print('key', key)
        print('value', value)
    return render(request, 'webapp/index.html', context)

How to render these key value pairs in the template, is it related to this https://code.djangoproject.com/ticket/16335 if so can someone suggest a solution

index.html

<div class="results">
        {% for key, value in context.items %}
            <h3>something</h3>
            {{key}}
            {{value}}
        {% endfor %}
</div>

The above for loop doesn't put anything in the template, but the same for loop in the views.py prints key value pairs in the terminal

  • I'm not sure but aren't you missing a `()` in `context.items` used in the template `index.html`? – accdias Aug 14 '21 at 16:35
  • no it gives an error, () cannot be used in templates I think – AKHIL SHALIL Aug 14 '21 at 16:39
  • Does this answer your question? [Rendering a python dict in Jinja2 / Werkzeug](https://stackoverflow.com/questions/19141073/rendering-a-python-dict-in-jinja2-werkzeug) – accdias Aug 14 '21 at 16:40
  • You could convert `context.items()` to a list before passing it to the template, and use the tuple indexes `{% for item in context_items_list %} {{ item.0 }} {{item.1 }}...` perhaps? – snakecharmerb Aug 14 '21 at 16:44
  • Just show context like this ```{{context}}``` and see if it shows anything. – Ram Aug 14 '21 at 16:45
  • {{ context }} or anything doesn't show up there like the dictionary is empty – AKHIL SHALIL Aug 14 '21 at 16:48
  • You are printing that in your views.py. Does it show anything there ? – Ram Aug 14 '21 at 16:50
  • yes the strange thing is it prints all the key value pairs in the terminal when the view is called – AKHIL SHALIL Aug 14 '21 at 16:52

0 Answers0