我正在Django中编写一个基本的RSS提要阅读器。我有一个表单,用户提交rss提要,然后将其添加到他的提要列表中。但由于某些原因,我无法使用Feed解析器提取有关Feed的基本信息。
当我运行以下代码时:
def form_valid(self, form):
user = self.request.user
link = form.cleaned_data['link']
feed = feedparser.parse(link).feed
title = feed.title
try:
feed_obj = Feed.objects.get(link=link)
except ObjectDoesNotExist:
feed_obj = Feed(link=link, title=title)
feed_obj.save()
user.get_profile().feeds.add(feed_obj)
return super(DashboardView, self).form_valid(form)
Django在第5行引发了一个“对象没有属性'标题'”例外:
title = feed.title
完整的错误详情如下:
Traceback:
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/home/yaniv/nextfeed/profiles/views.py" in form_valid
48. title = feed.title
File "/home/yaniv/nextfeed/venv/local/lib/python2.7/site-packages/feedparser.py" in __getattr__
416. raise AttributeError, "object has no attribute '%s'" % key
Exception Type: AttributeError at /dashboard
Exception Value: object has no attribute 'title'
我做错了什么?
编辑:我用pdb跟踪了程序。就在问题线之前,我得到了:(Pdb) link
u'http://feedparser.org/docs/examples/rss20.xml'
(Pdb) feed
{'xhtml_script': {'type': u'text/javascript', 'language': u'javascript'}, 'summary': u''}
答案 0 :(得分:0)
自从我使用feedparser已经有一段时间了,但是IIRC,解析器会返回一个字典,如下所示:
foo = feedparser.parse(link)
feed = foo['feed']
title = feed['title']
你好像从foo.feed那里得到了一个对象,但那不是你想要的。