首页 > 解决方案 > 如何在python的html文件中写入json数据

问题描述

我有这个 json 数据{'latest_question_list': ((1, "What's up?", datetime.datetime(2019, 4, 19, 7, 38, 6, 449735)),)},我想在我的 html 文件中显示这个数据,任何人都可以帮助我如何在其中显示这个数据,这是我添加的整个代码,任何人都可以帮我解决这个问题,我也需要帮助为什么我在元组中得到数据库结果?

模型.py

import datetime
from django.utils import timezone
from django.db import connection
from django.db import models


class Question():
    @classmethod
    def get_poll_question(cls):
        with connection.cursor() as cursor:
            db_table = "polls_question"
            cursor.execute('SELECT * FROM '+db_table)
            allquestion = cursor.fetchall()
            return allquestion

class Choice():
    def get_options(cls):
        with connection.cursor() as cursor:
            db_table = "polls_choice"
            cursor.execute("SELECT * FROM "+ db_table+" WHERE question_id = '1' ")
            choice_text = cursor.fetchall();
            return choice_text

视图.py

from django.shortcuts import render

# Create your views here.


from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Choice, Question
from django.urls import reverse
from django.shortcuts import get_object_or_404, render



def index(request):
    latest_question_list = Question.get_poll_question()
    context = {'latest_question_list': latest_question_list}
    print(context)
    return render(request, 'polls/index.html', context)

索引.html

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

标签: pythondjango

解决方案


您可以简单地在 html 中使用双括号 {{}},如下所示:

{{ latest_question_list }}

推荐阅读