[英]How to loop over dictionary to display in frontend in django and implement user input
我已經從tweepy api結果創建了自己的字典。
它在前端顯示我想要的數據。 但是,我該如何遍歷字典,以便為創建的每個字典生成html。
我也希望讓用戶輸入確定查詢參數,但不確定如何做
這是我嘗試過的,但無濟於事。
{% for tweet in twitter_data %}
<div class="tweet-container">
<img src="{{twitter_data.profile_dp}}" alt="avatar" class="avatar" />
<time class="tweet-time">{{twitter_data.created_at}}</time>
<div class="push">
<div class="user">
<div class="user-string"><span class="name">{{twitter_data.user_name}}</span><span
class="username">@{{twitter_data.user_screen_name}}</span></div>
</div>
<blockquote class="tweet"><span class="at">@lorem_bot </span>{{twitter_data.text}} <span
class="tag">#lorem2015</span></blockquote>
<div class="icons">
<i class="fa fa-reply"><span class="icon-number"> 10</span></i>
<i class="fa fa-retweet"><span class="icon-number"> {{twitter_data.retweet_count}}</span></i>
<i class="fa fa-star"><span class="icon-number"> {{twitter_data.fav_count}}</span></i>
<i class="fa fa-ellipsis-h"></i>
<i class="fa fa-eye"></i>
</div>
</div>
</div>
{% end for %}
from django.shortcuts import render
import requests
import tweepy
import json
# Create your views here.
CONSUMER_KEY = 'm'
CONSUMER_SECRET = 'Xu'
ACCESS_KEY = '116'
ACCESS_SECRET = 'wz'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
def index(requests):
for tweet in tweepy.Cursor(api.search,
query="xbox",
q="{xbox}",
count=1,
result_type="recent",
include_entities=True,
lang="en").items():
twitter_data = {
'text': tweet.text,
'user_name': tweet.user.name,
'user_screen_name': tweet.user.screen_name,
'created_at': tweet.created_at,
'profile_dp': tweet.user.profile_image_url,
'retweet_count': tweet.retweet_count,
'fav_count': tweet.favorite_count
}
context = {'twitter_data': twitter_data}
return render(requests, 'twitter/twitter.html', context)
您無需在模板中運行多個循環。 您只需要在視圖中將這些tweet對象保存為列表,然后在模板中對其進行循環。
#views.py
tweets = tweepy.Cursor(api.search,
query="xbox",
q="{xbox}",
count=1,
result_type="recent",
include_entities=True,
lang="en").items()
context = {'tweets': tweets}
然后在您的模板中:
{% for tweet in tweets %}
{{ tweet.text }}
{{ tweet.user.name }}
{{ tweet.retweet_count }}
{% endfor %}
等等....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.