Frendom
Frendom

Reputation: 558

Django - calling function does not redirect

I want to redirect and return view after submiting form on my homepage. Unfortunately after POST nothing is happend.

My homepage:

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')

Of course I send other attributes like dictionaries etc, but it works fine when I hardcode my url in browser. After clicking submit on my form in my homepage nothing is happend.

EDIT

my bokeh function look like that:

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})

and my urls.py

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

And at this moment I got TypeError: url() got an unexpected keyword argument 'url'

Upvotes: 1

Views: 917

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You did not return the result of the bokeh function:

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

Note however that this is not redirecting, and therefore you do not implement the Post/Redirect/Get pattern [wiki]. In case of a successful POST request, it is usually a good idea to perform a redirect, to prevent a user from refreshing the page, making the same POST request. A POST request frequently has side effects, and therefore we want to omit that.

You better make use of the redirect(..) function [Django-doc] here:

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')

You should not use a url=… in the url(..) function:

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

Upvotes: 3

Related Questions