我正在尝试访问由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 %}
author_name
,所以我get_context_data
函数替换为返回 item.author
和 Boom 的item_author_name
函数!我通过模板中的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