简体   繁体   中英

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

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 class="left">{{ entry }}</div>
<div class="right">
    <a href="{% url 'edit' %}">
        <button class="edit">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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM