gpt4 book ai didi

python - Django - 调用函数不重定向

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:31 24 4
gpt4 key购买 nike

我想在我的主页上提交表单后重定向并返回 View 。不幸的是,在 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 时,它工作正常。在我的主页上点击我的表单提交后,没有任何反应。

编辑

我的 Bokeh 功能看起来像这样:

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'

最佳答案

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

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

但是请注意,这不是重定向,因此您不会实现 Post/Redirect/Get pattern [wiki] .如果 POST 请求成功,执行重定向通常是个好主意,以防止用户刷新页面,发出相同 POST 请求。 POST 请求经常有副作用,因此我们希望忽略它。

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

from django.shortcuts import <b>redirect</b>

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

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

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

关于python - Django - 调用函数不重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com