【问题标题】:How to access data in get_context_data RSS Feed django 2.2如何在 get_context_data RSS Feed django 2.2 中访问数据
【发布时间】:2019-08-05 23:56:23
【问题描述】:

我正在尝试访问由 LatestVideosFeed 中修改后的“get_context_data”函数返回的上下文字典,因此我可以在我尝试创建的“新闻提要”中使用它,因为返回的上下文包含视频的作者。 我一直在关注这些文档https://docs.djangoproject.com/en/2.2/ref/contrib/syndication/,但我不知道如何访问从get_context_data(self, item, **kwargs): 返回的上下文字典它可以工作,当我在返回之前进行调试打印时,它返回一个字典,最后一个条目作为上传视频的用户。调试打印是print(context['author']),每次与提要交互时都会按预期返回。

feeds.py

class LatestVideosFeed(Feed):
    link = '/video-feeds/'
    description = 'New Video Posts'

    def items(self):
        return VideoPost.objects.all()

    def get_context_data(self, item, **kwargs):
        context = super().get_context_data(**kwargs)
        context['author'] = item.author
        print(context['author'])
        return context

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.description

    def item_link(self, item):
        return reverse('video_post', args=[item.pk])

views.py

def video_list(request):
    feeds = feedparser.parse('http://localhost:8000/profs/video-feeds')
    return render(request, 'vids/video_list.html', {'feeds': feeds})

模板

{% for thing in feeds.entries %}
        <h1>Author</h1><br>
        {{thing.author}} <-- Nothing is printed here
        <h1>Title</h1>
        {{thing.title}}<br>
        <h1>Description</h1>
        {{thing.summary}}<br>
        <h1>Video Link</h1>
        <a href="{{thing.link}}">{{thing.title}}</a><br>
{% endfor %}


【问题讨论】:

  • 不清楚您的问题是什么。您希望在何处以及如何访问上下文以及为什么?
  • 我想在我正在尝试制作的“新闻提要”中显示作者(在上下文中)。我一直在通过循环访问其他字段 feeds.entries where feeds = feedparser.parse('http://localhost:8000/profs/video-feeds')
  • 啊,那么问题是为什么 feedparser 没有返回您添加到 Feed 中的自定义属性?
  • 对,对不起。自从我有一个小时左右的休息时间醒来后,我就一直在编程。我的大脑被炸了。谢谢大声笑
  • 别担心!看过 feedparser 后,它似乎只使用了 FeedParserDict 的实例,这似乎不允许自定义属性

标签: django django-views rss django-rss django-syndication


【解决方案1】:

我对我提供的文档进行了更多阅读,并注意到 SyndicationFeed 允许您添加项目,其中一个参数是 author_name,因此我将 get_context_data 函数替换为返回 @ 的 item_author_name 函数987654324@ 和繁荣!我通过模板中的feeds.entries 循环访问它(下面的旧代码和新代码以获得更好的上下文)

# Old Code
def get_context_data(self, item, **kwargs):
        context = super().get_context_data(**kwargs)
        context['author'] = item.author
        print(context['author'])
        return context 
# New Code
def item_author_name(self, item):
        print('Being Called')
        return item.author

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 2012-01-03
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多