Home > OS >  How do I access data from a dictionary in a HTML template?
How do I access data from a dictionary in a HTML template?

Time:07-17

When I try to use data from a dictionary, I get the error:

'tuple' object has no attribute 'get'

This happens when I click on a link that should take me to the page of the entry. The entry is a Markdown file that I get from util.get_entry(title).

How do I access data from a dictionary in my HTML template (entry.html)? Do I need to convert the Markdown into HTML?

entry.html:

{% extends "encyclopedia/layout.html" %}

<!-- {% load static %} -->

{% block title %}
{{ name }}
{% endblock %}

{% block style %}{% endblock %}

{% block body %}
<div >{{ entry }}</div>
<div >
    <a href="{% url 'edit' %}">
        <button >Edit</button>
    </a>
</div>
{% endblock %}

views.py:

from . import util

def entry(request, name):
    if util.get_entry(name) is not None:
        return render(request, 'encyclopedia/entry.html'), {
            'entry': util.get_entry(name),
            'name': name
        }
    else:
        return render(request, "encyclopedia/404.html")

urls.py:

path('<str:name>', views.entry, name='entry'),

util.py:

def get_entry(title):
    """
    Retrieves an encyclopedia entry by its title. If no such
    entry exists, the function returns None.
    """
    try:
        f = default_storage.open(f"entries/{title}.md")
        return f.read().decode("utf-8")
    except FileNotFoundError:
        return None

CodePudding user response:

You are not passing the dict in parameters. Please use this

from . import util

def entry(request, name):
    if util.get_entry(name) is not None:
        context ={ 
            'entry': util.get_entry(name),
            'name': name

        }
        return render(request, 'encyclopedia/entry.html',context)
    else:
        return render(request, "encyclopedia/404.html")
  • Related