【问题标题】:Django - calling function does not redirectDjango - 调用函数不重定向
【发布时间】:2019-11-13 22:25:20
【问题描述】:

我想在主页上提交表单后重定向并返回视图。不幸的是,POST 之后什么都没有发生。

我的主页:

def home(request):
    if request.method == 'POST':
        url = request.POST['url']
        bokeh(request,url)
    return render(request,'home.html')

def bokeh(request,url):
    //my calculation logic
    return render(request,'bokeh.html')

当然,我会发送其他属性,例如字典等,但是当我在浏览器中硬编码我的 url 时,它可以正常工作。在我的主页中单击我的表单上的提交后,没有任何反应。

编辑

我的散景功能是这样的:

def bokeh(request,url):

    source = urllib.request.urlopen(url).read()
    soup = bs.BeautifulSoup(source, 'lxml')
    descrp = [description.text for description in soup.find_all('p', class_="commit-title")]
    author = [author.text for author in soup.find_all('a', class_="commit-author")]
    dict1 = dict(zip(descrp,author))
    dict2 = dict(Counter(dict1.values()))
    label = list(dict2.keys())
    value = list(dict2.values())

    plot = figure(title='Github Effort',x_range=label,y_range=(0,30), plot_width=400, plot_height=400)
    plot.line(label,value,line_width = 2)
    script,div = components(plot)

    return render(request,'bokeh.html',{'script': script,'div': div})

还有我的 urls.py

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^bokeh/(?P<url>\w+)/$',views.bokeh,name='bokeh',url='url'),
]

此时我得到了 TypeError: url() got an unexpected keyword argument 'url'

【问题讨论】:

标签: python django redirect


【解决方案1】:

你没有返回bokeh函数的结果:

def home(request):
    if request.method == 'POST':
        url = request.POST['url']
        return bokeh(request,url)
    return render(request,'home.html')

但是请注意,这不是重定向,因此您确实实现Post/Redirect/Get pattern [wiki]。在成功的 POST 请求的情况下,执行重定向通常是一个好主意,以防止用户刷新页面,使 same POST 请求。 POST 请求经常有副作用,因此我们想省略它。

你最好在这里使用redirect(..) function [Django-doc]

from django.shortcuts import redirect

def home(request):
    if request.method == 'POST':
        url = request.POST['url']
        return redirect('bokeh', url=url)
    return render(request,'home.html')

您不应在url(..) 函数中使用url=…

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^bokeh/(?P<url>\w+)/$', views.bokeh, name='bokeh'),
]

【讨论】:

  • 好的,所以第一种方法工作正常 - 我得到了我想要的,但它仍然在同一个端点(只是主页更改的内容,没有重定向到 localhost:8000/bokeh 我所期望的。第二种方法不起作用 - 可能我的 urls.py (url(r'^bokeh/',views.bokeh,name='bokeh')) 有问题
  • @Frendom:不,没有重定向。您只需调用函数,并返回该函数的响应。如前所述,首先调用该函数也不是一个好主意。您应该返回一个带有bokeh 视图名称的redirect,然后让客户端发出第二个请求。
  • @Frendom:因为那个视图的名字是bokeh,所以它应该是redirect('bokeh', url=url)。但是你忘了给你url(..)添加一个(?P&lt;url&gt;...)参数。见:docs.djangoproject.com/en/2.0/ref/urls/#django.urls.re_path
  • @Frendom:你应该省略url='url' 参数。
  • 我得到 NoReverseMatch 的 'bokeh' 关键字参数 '{'url': 'url I just sent'}'
猜你喜欢
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-11
  • 1970-01-01
  • 2016-03-13
相关资源
最近更新 更多