首页 > 解决方案 > 推文不会嵌入 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,推文将自行嵌入。我工作了几天,它仍然不起作用。

标签: pythondjangotwitterembed

解决方案


您只能看到 HTML 而不是实际的推文,因为{{tweets}}只会呈现转义的 HTML。如果您需要呈现该 HTML,您可以使用safe过滤器:

{{tweets|safe}}

另请查看此 SO 帖子:将模板变量呈现为 HTML


推荐阅读