【问题标题】:How to send POST data to a reversed url如何将 POST 数据发送到反向 url
【发布时间】:2013-11-02 07:10:57
【问题描述】:

我有 HttpResponseRedirect() 构造所需 url 的函数:

我的create 观点:

def create(request):
    entry = Char_field(field=request.POST['record'])
    entry.save()
    return HttpResponseRedirect(reverse('db:index_page',kwargs={'redirected':'true'}))

HttpResponseRedirect()重定向到的视图是:

def index(request):
    redirected = False
    template= 'app/index.html'
    try:
        if request.POST['redirected'] is 'true':
            redirected = True
    except:
        pass
    return render(request,template,{'redirected':redirected})

但是它返回一个错误:

NoReverseMatch at /app/create/
Reverse for 'index_page' with arguments '()' and keyword arguments '{'redirected': 'true'}' not found.

urls.py:

urlpatterns = patterns('',
    url(r'^$',views.index,name='index_page'),
    url(r'^get_record/$',views.get_record,name='get_record'),
    url(r'^create/$',views.create_html,name='create_path'),
    url(r'^add/$',views.create,name='add_record')
)

为什么会这样?是否可以通过reverse() 函数将POST 数据发送到index_page 视图?

【问题讨论】:

  • 向我们展示您的urls.py 以及db:index_page 的定义。
  • 很清楚:index_name 在 URL 定义中不带任何参数,所以reverse 找不到位置并抛出错误。
  • @Matthias 这就是重点,我正在尝试通过reverse 函数将数据作为POST 请求发送
  • @KDawG 好吧,你不能这样做,因为那样你就需要更改标题。
  • HTTP 重定向不能包含 POST 数据。有关详细信息和可能的解决方案,请参阅stackoverflow.com/questions/3024168/…

标签: python django python-2.7 http-post


【解决方案1】:

这个问题实际上与 POST 数据无关。您只是尝试使用参数进行反转,但 index_page 的 URL 不包含参数。无论您是否要发布到该 URL,这都是正确的。

然后,当然,您实际上 POST 到该 URL,您只需返回 HttpResponseRedirect,它会执行 302 重定向。

我不确定您为什么认为在 POST 中需要此参数。如果你不想把它放在 URL 模式中,为什么不把它放在 GET 参数中呢?

url = reverse('db:index_page') + '?redirected=true'
return HttpResponseRedirect(url)

在接收视图中:

redirect = request.GET.get('redirected')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2011-09-20
    • 2020-06-20
    相关资源
    最近更新 更多