python - 推文不会嵌入 django
问题描述
这是我的 Django Twitter 项目的 html。我正在尝试在 Django 中嵌入推文
<html lang="en">
<h1>Tweets</h1>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
<body>
{% if tweets %}
<p>{{tweets}}<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p>
{% endif %}
</body>
</html>
这是我的views.py:
import tweepy
from tweepy.auth import OAuthHandler
from .models import Tweet
from .models import Dates
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.shortcuts import render
from django.db import models, transaction
from django.db.models import Q
import os
import tweepy as tw
from .forms import TweetIDForm
from django import template
import requests
consumer_key = 'dddddd'
consumer_secret = 'cccccc'
access_token = 'dddddd'
access_token_secret = 'ccccc'
def clean_tweet_id(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = TweetIDForm(request.POST)
print(form)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
tweet_id = form.cleaned_data.get("tweet_id")
#act = form.cleaned_data.get("action")
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)
twtjson = requests.get('https://publish.twitter.com/oembed?url=' + tweet_id + '&omit_script=true')
tweets = twtjson.json()
tweet = tweets.get('html')
return render(request, 'tweet/tweet-list.html', {'form': form, 'tweet_id':tweet_id, 'tweets': tweet})
到目前为止,我的代码可以正常工作,但由于某种原因,它没有显示实际的推文,而只是显示了 HTML,而不是实际的推文,就像它会嵌入到另一个站点一样。我正在尝试创建一个应用程序,用户在其中输入推文 URL,推文将自行嵌入。我工作了几天,它仍然不起作用。
解决方案
您只能看到 HTML 而不是实际的推文,因为{{tweets}}
只会呈现转义的 HTML。如果您需要呈现该 HTML,您可以使用safe
过滤器:
{{tweets|safe}}
另请查看此 SO 帖子:将模板变量呈现为 HTML。
推荐阅读
- java - 如何在 Android 中的 Activity 之间切换时保存数据
- android - 当我打开 Google 地图活动时,当前位置未首次显示
- python - 在 python 中解压 .gz 文件时出错
- mysql - Laravel hasOneThrough 或者通过中间表获取关系
- list - Flutter:我如何在列表中实现列表?错误:在 initializers.dart(implicit_this_reference_in_initializer) 中只能访问静态成员
- r - 闪亮:在空/未选择的radioButtions()的情况下,actionButton()可以返回错误吗?
- c# - 如何检查 JsonPath 中的多个键
- python - Scrapy - 一次运行多个蜘蛛 - CrawlerProcess - 文件结构
- docker - docker容器中的xcodebuild
- javascript - 在执行下一个操作之前等待循环完成