例外值:字匹配查询不存在。查找参数是{'word__iexact':u'abc / action'}

时间:2013-03-12 10:13:17

标签: django

我正在使用Django urls.py从网址中提取值,这是我的urls.py

urlpatterns = patterns('',
    url(r'^word/(?P<w>.+)/$', 'myapp.views.word'),
    url(r'^word/(?P<w>.+$)/action/', 'myapp.views.action'),)

第一项:myapp.views.word效果很好并接受输入的变量/word/asdf,我可以操纵asdf我在views.py中的选择。 第二项myapp.views.action给出了错误

Exception Value:    
Word matching query does not exist. Lookup parameters were {'word__iexact': u'asdf/action'}

这是我views.py的一部分:

def action(request, w):
    o = Word.objects.get(word__iexact=w)

我希望当用户转到/word/asdf/action时,我可以在action参数上运行asdf视图。我做错了什么?

2 个答案:

答案 0 :(得分:2)

你错位$这就是为什么行动在你的参数

urlpatterns = patterns('',
    url(r'^word/(?P<w>.+)/$', 'myapp.views.word'),
    url(r'^word/(?P<w>.+)/action/$', 'myapp.views.action'),)

答案 1 :(得分:1)

您收到此错误是因为r'.+'也匹配“/”字符,并且它会贪婪,因此它会匹配URL的所有最后部分。因此,您永远不会调用第二个定义,/asfd//asfd/action/都会匹配^word/(?P<w>.+)/$ (见https://docs.djangoproject.com/en/dev/topics/http/urls/#how-django-processes-a-request,第3点)

在你的url.py中试试这个:

 url(r'^word/(?P<w>.+)/(?P<action>.+)/$', 'myapp.views.action'),)

和你的views.py

def action(request, w, action):
    o = Word.objects.get(word__iexact=w)
    # do something with "action" variable and "o" object
    #...

OTHERWISE 你可以简单地使用一个不那么贪婪的正则表达式:

     url(r'^word/(?P<w>\w+)/$', 'myapp.views.word'),)
     url(r'^word/(?P<w>\w+)/action/$', 'myapp.views.action'),)
     url(r'^word/(?P<w>\w+)/draw/$', 'myapp.views.draw'),)
     # and so on...

有关详细信息,您可以随时参考python docs(http://docs.python.org/2/library/re.html#regular-expression-syntax