我无法让Django运行带参数的Tweepy脚本。当我启动服务器并创建一个实例时,我似乎能够让脚本运行print语句,但是我很难让它从HTML输入中获取标记。
HTML按钮:
<div class="col s12">
<div class="input-field inline">
<label for="User">Enter a term</label>
<form action = "submit/" method = "post">
{% csrf_token %}
<input id="Country" type="text" name="Country" maxlength="100" required value="{{ tag }}" />
<button class="btn waves-effect red" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
</div>
Views.py
from django.shortcuts import render
from .forms import GetTweets
from . import live
# Create your views here.
#Index by Kenny P
def index(request):
context = {'tag': ''}
return render(request, 'visualize/index.html', context)
#Tweets by Kenny P. Tweet will return the tweets
def Tweets(request):
#Terms we want displayed go here!
print 'IN!!!'
if request.method == 'POST':
info = GetTweets(request.POST)
if info.is_valid():
country = request.POST['Country']
tw = live.GetTweets(render_data.cleaned_data['Country'])
else:
country = GetTweets()
context = {
'Country': country,
}
return render(request, 'visualize/index.html', context)
def submit(request):
return render(request, 'visualize/index.html')
forms.py
from django import forms
#Search for the tag
class GetTweets(forms.Form):
user = forms.CharField(label='User', max_length=30)
最后,(临时)tweepy脚本:
import tweepy
import time
from collections import defaultdict
import json
consumer_key = "??"
consumer_secret = "??"
access_key = "??"
access_secret = "??"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
def GetTweets(tag):
placeholder = []
for tweet in tweepy.Cursor(api.search, q=tag).items(20):
placeholder.append(tweet.created_at)
placeholder.append(tweet.text)
#created_at
print ' placeholder 0 \n'
print placeholder[0]
print placeholder[1]
print ' placeholder 1\n'
print placeholder[2]
print placeholder[3]
URLS
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^submit', views.Tweets),
]
答案 0 :(得分:0)
您必须将listView.setOnGroupClickListener(mListener);
传递给您的模板,否则tag
将为空。更改您的{{ tag }}
视图(iirc,在旧版本的Django中,您需要在index()
中包含上下文字典:
template.Context(context)
将您的html更改为发布到正确的网址,例如:
context = {'tag': 'hello world']
return render(request, 'visualize/index.html', context)
确保urls.py匹配(您最后缺少<form action="submit/" method="post">
):
/$
你的urls.py也需要匹配视图定义。如果您将视图定义为采用url(r'^submit/$', views.Tweets),
参数:
tag
然后urls.py需要捕获名为def Tweets(request, tag):
的字段,例如:
tag
但是,由于您将url(r'^submit/(?P<tag>\w+)/$', views.Tweets),
变量作为Country
变量传递,因此您的网址应为
POST
并且应该在没有标记参数的情况下定义视图
url(r'^submit/$', views.Tweets),