无效的块标记:' gettweet',expect' endblock'对于Django项目

时间:2014-06-07 02:19:12

标签: python django django-templates django-views

我正在学习Django,我正在尝试使用twitter API测试获取推文并将其显示在页面上。 我的views.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'])

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

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

我无法弄清楚为什么我会收到此错误,请帮助我,谢谢。

1 个答案:

答案 0 :(得分:1)

你不能用这种方式从模板中调用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 %}