gpt4 book ai didi

python - Django 项目的 block 标记无效 : 'gettweet' , 应为 'endblock'

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:18 25 4
gpt4 key购买 nike

我正在学习 Django,我正在尝试测试使用 twitter API 获取推文并将其显示在页面上。我的观点.py 说

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from firstsite.website import twit
# Create your views here.
class IndexView(TemplateView):
template_name = 'firstsite/templates/index.html'

我的index.html说

{% extends "firstsite/templates/base/base.html" %}
{% block title %}The home page{% endblock %}
{% block base_content %}
{% gettweet %}
{% endblock %}

twit.py 说

from twython import Twython
import json
def gettweet():
APP_KEY= 'somekey'
APP_SECRET = 'somesecretkey'

twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter1 = Twython(APP_KEY, access_token=ACCESS_TOKEN)
data1 = twitter1.search(q='python', count=1)
return(data1['statuses'][0]['text'])

当我尝试访问该 View 时,出现此错误

TemplateSyntaxError at /
Invalid block tag: 'gettweet', expected 'endblock'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.6.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid block tag: 'gettweet', expected 'endblock'
Exception Location: /usr/local/lib/python3.4/dist-packages/django/template/base.py in invalid_block_tag, line 331
Python Executable: /usr/bin/python3.4
Python Version: 3.4.0
Python Path:
['/home/lonewaft/webdev/firstsiteproject',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/usr/lib/python3.4/lib-dynload',
'/usr/local/lib/python3.4/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sat, 7 Jun 2014 02:14:43 +0000

我不明白为什么会出现此错误,请帮助我,谢谢。

最佳答案

您不能以这种方式从模板调用 python 函数。在你看来,称之为add the result to a template context并在模板中显示:

import twit

class IndexView(TemplateView):
template_name = 'firstsite/templates/index.html'

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['tweet'] = twit.gettweet()
return context

然后,在模板中:

{% extends "firstsite/templates/base/base.html" %}

{% block title %}The home page{% endblock %}

{% block base_content %}
{{ tweet }}
{% endblock %}

关于python - Django 项目的 block 标记无效 : 'gettweet' , 应为 'endblock',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24093018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com