【问题标题】:Reverse for ‘<a_view>' with arguments '()' and keyword arguments '{'id': None}' not found未找到带有参数“()”和关键字参数“{'id': None}”的“<a_view>”的反向
【发布时间】:2016-06-15 14:48:52
【问题描述】:

我遇到了一个“NoReverseMatch”异常,有一个反向。

未找到带有参数“()”和关键字参数“{'id': None}”的“notifications_read”的反向操作。尝试了 1 种模式:['notifications/read/(?P\d+)/$']

我正在尝试检查何时在 cmets 上读取通知。基本上,到目前为止我已经掌握了这个:

url.py:

url(r'^notifications/read/(?P<id>\d+)/$', notifications.views.read, name='notifications_read')

而且问题似乎出现在Notification类中,在str(self)方法中:

notifications/models.py

context = {
    "sender": self.sender_object,
    "verb": self.verb,
    "target": self.target_object,
    "action": self.action_object,
    "verified_read": reverse('notifications_read', kwargs={"id": self.id}),
    "target_url": target_url,
}
return "{sender} {verb} <a href='{verified_read}?next={target_url}'>{target}</a> with {action}.".format(**context)

我无法弄清楚为什么 self.id 是 None 这似乎是问题,因为当我在 URL 模式中取下它时,以及反过来的 kwargs 时,我不要得到异常(但也不是所需的 URL)。

如果我把 str(self.id) 设为:

reverse('notifications_read', kwargs={'id': str(self.id)})

url(r'^notifications/read/(?P<id>[\w-]+)/$', notifications.views.read, name='notifications_read')

没有例外,但呈现的是/notifications/read/None/

我知道有很多类似的问题,比如Reverse for '*' with arguments '()' and keyword arguments '{}' not found

但在其中没有一个,self.id 返回 None 似乎存在这个问题。

我正在使用 Django 1.9.2 和 python 3.5

你能帮忙吗?这将不胜感激。 非常感谢!

如果有帮助,当我评论这些行时也不会发生异常:

cmets/views.py

notify.send(
    request.user,
    action=new_comment,
    target=parent_comment,
    recipient=parent_comment.user,
    verb="replied to"
)

这是notifications/views.py中对应的视图:

@login_required
def read(request, id):
    try:
        next = request.GET.get('next', None)
        notifications = Notification.objects.get(id=id)
        if notifications.recipient == request.user:
            notifications.read = True
            notifications.save()
            if next is not None:
                return HttpResponseRedirect(next)
            else:
                return HttpResponseRedirect(reverse("notifications_all"))
        else:
            raise Http404
    except:
        raise HttpResponseRedirect(reverse("notifications_all"))

调试页面上,我得到:

Request Method: POST

Request URL: http://0.0.0.0:8000/comment/create/

Django Version: 1.9.2

Exception Type: NoReverseMatch

Exception Value: Reverse for 'notifications_read' with arguments '()' and keyword arguments '{'id': None}' not found. 1 pattern(s) tried: ['notifications/read/(?P<id>\\d+)/$']

Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 508

Python Executable:/Library/Frameworks/Python.framework/Versions/3.5/bin/python3

Python Version:3.5.0

EDIT 2(完整追溯):

Environment:


Request Method: POST
Request URL: http://0.0.0.0:8000/comment/create/

Django Version: 1.9.2
Python Version: 3.5.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'accounts',
 'comments',
 'notifications',
 'videos']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/leomaltrait/PycharmProjects/srvup/src/comments/views.py" in comment_create_view
  80.                     verb="commented on"

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/dispatch/dispatcher.py" in send
  192.             response = receiver(signal=self, sender=sender, **named)

File "/Users/leomaltrait/PycharmProjects/srvup/src/notifications/models.py" in new_notification
  157.     print(new_note)

File "/Users/leomaltrait/PycharmProjects/srvup/src/notifications/models.py" in __str__
  95.             "verified_read": reverse('notifications_read', kwargs={"id": self.id}),

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/urlresolvers.py" in reverse
  600.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
  508.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /comment/create/
Exception Value: Reverse for 'notifications_read' with arguments '()' and keyword arguments '{'id': None}' not found. 1 pattern(s) tried: ['notifications/read/(?P<id>\\d+)/$']

【问题讨论】:

  • context = ... 代码块在您的模型中的什么位置?你能展示你的完整模型吗?
  • URL http://0.0.0.0:8000/comment/create/ 出现错误。您似乎没有显示该网址的视图。
  • 看起来object 尚未创建。所以它没有id
  • 感谢您的回答。我使用完整模型和对应于 /comment/create/ 的视图编辑了问题(在问题底部的 EDIT 之后)。我想尽可能少地为您提供更多信息,但似乎还不够(我是新手)
  • 这是来自调试页面的完整回溯吗?

标签: python django python-3.x


【解决方案1】:

我发现了问题。这是我们可以在 Traceback: print(new_note) 中看到的 print 语句。它是另一种方法 (new_notification) 的一部分。

我什至不知道打印会导致异常。特别是因为 new_note 对象似乎存在(通知在没有此打印语句的情况下运行良好)。

无论如何,非常感谢您的时间和帮助!

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2013-12-07
    • 2015-08-29
    • 2014-05-29
    • 2013-07-25
    • 2019-11-06
    • 2012-07-08
    • 2019-04-21
    相关资源
    最近更新 更多