Search code examples
djangohttphttp-redirectwebresponse

DJANGO: Redirect to a page based on a submitted data form (HttpResponseRedirect)


I'm new with django and I'm trying to redirect to a page based on a submitted data form, but no luck. Is there a method with the HttpReponseRedirect I can pass or just the syntax is not right? I tried figuring it out but failed.

views.py

...
def select_bar(request):
    if request.method == 'POST':
        form = SelectBarForm(request.POST)
        if form.is_valid():
            bar = form.cleaned_data['bar']
            bar_name = str(bar.name)
            return HttpResponseRedirect('/bars/(?P<bar_name>\w+)/')
            # return HttpResponseRedirect('/')
    else:
        form = SelectBarForm()
        return render_to_response('bars_templates/bars.html', {'form': form}, RequestContext(request))
    ...

urls.py

...
urlpatterns += patterns('bars.views', (r'^bars/$', 'select_bar'),)
urlpatterns += patterns('songs.views', (r'^bars/(?P<bar_name>\w+)/$', 'songs'),) # capture the bar name from the url.
...

Solution

  • I'm not quite sure why you have used a regex there. You need to use an actual URL:

    return HttpResponseRedirect('/bars/%s/' % bar_name)
    

    or even better use the reverse function which accepts a view name and the relevant parameters

    return HttpResponseRedirect(reverse('songs.views.songs', bar_name=bar_name))
    

    or even better again, use the redirect function which does both the reversing and the redirecting:

    return redirect('songs.views.songs', bar_name=bar_name)