【问题标题】:Invalid block tag: 'gettweet', expected 'endblock' for Django project无效的块标签:'gettweet',Django 项目的预期'endblock'
【发布时间】:2014-06-07 02:19:12
【问题描述】:

我正在学习 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

我不知道为什么会出现这个错误,请帮助我,谢谢。

【问题讨论】:

  • gettweet 来自哪里?
  • @alecxe 我也会添加该代码,抱歉。

标签: python django django-templates django-views


【解决方案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 %}

【讨论】:

  • 谢谢,这很完美,只需将context['tweet'] = gettweet() 更改为context['tweet'] = twit.gettweet()
  • @lonefaft gotcha,编辑了答案以遵循您的注释。
猜你喜欢
  • 2012-05-03
  • 1970-01-01
  • 2014-01-06
  • 2012-02-07
  • 2015-04-19
  • 2015-02-10
  • 2012-03-09
  • 2018-09-01
  • 2015-09-16
相关资源
最近更新 更多