使用HttpResponseRedirect重定向到python中的另一个函数

时间:2015-03-06 16:21:27

标签: python exception redirect httpresponse reverse

我有一个功能:

def drawback(request,problem_id) 

我希望在此函数的最后重定向到从函数

调用的另一个页面
def show(request,problem_id)

我试过

return HttpResponseRedirect(reverse('show',kwargs={'problem_id':10}))
return HttpResponseRedirect(reverse('show',kwargs={'problem_id':'10'}))
return HttpResponseRedirect(reverse('show',args=[10]))
return HttpResponseRedirect(reverse('show',args=(10))

我在其他网站上发现的一切。但我收到错误

Exception Type:     NoReverseMatch
Exception Value:    

Reverse for 'show' with arguments '()' and keyword arguments '{'problem_id': '10'}' not found.

Exception Value: Reverse for 'show' with arguments '(u'10',)' and keyword arguments '{}' not found.

当我通过带有按钮的html调用它时,此功能和页面正常工作。当我尝试从缺陷函数重定向时,无效。

urls.py

from django.conf.urls.defaults import *
from views import *
import settings
from django.conf import settings as rootsettings

urlpatterns = patterns('',
   # authentication
   (r'^start_auth', start_auth),
   (r'^after_auth', after_auth),

   # screens
   (r'^problems/codelookup$', code_lookup),

   # TESTING
   (r'^problems/test$', test_message_send),

   (r'^donnorsTool/$', problem_list),
   (r'^problems/delete/(?P<problem_id>[^/]+)', archived_problem),
   (r'^problems/edit/(?P<problem_id>[^/]+)', edit_problem),

   (r'^problems/restore/(?P<problem_id>[^/]+)', restore_problem),
   (r'^problems/new$', new_problem),
   (r'^problems/archived$', archived_problems),
   (r'^donnorsTool/show/(?P<problem_id>[^/]+)', show),
   (r'^donnorsTool/consent/(?P<problem_id>[^/]+)/(?P<counter>[^/]+)', consent),
   (r'^donnorsTool/withdraw/(?P<problem_id>[^/]+)/(?P<counter>[^/]+)', withdraw),

    # static
    ## WARNING NOT FOR PRODUCTION
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': rootsettings.SERVER_ROOT_DIR + settings.STATIC_HOME}),
)

3 个答案:

答案 0 :(得分:0)

只需将其称为函数:

def drawback(request,problem_id) 
    ...
    ...
    return show(request,10)

答案 1 :(得分:0)

From the docs,你可以做几件事。

# using the Python path
reverse('news.views.archive')

# using the named URL
reverse('news_archive')

# passing a callable object
from news import views
reverse(views.archive)

如果您想轻易更改视图名称,我更喜欢名称,所以

urls.py

中的

(r'^donnorsTool/show/(?P<problem_id>[^/]+)', show, name='show'),
views.py

中的

return HttpResponseRedirect(reverse('show',kwargs={'problem_id':10}))

答案 2 :(得分:0)

我找到了解决方案。我不确定它是否是最好的,但对我来说它的工作方式如下:

return HttpResponseRedirect('../../show/'+problem_id) 

我不知道是否会引起这样的问题。