简体   繁体   中英

Django: Redirecting to another url based on user input in form

I am trying to achieve something really simple and having no luck after reviewing the Django forms documentation as well as the section in the Django Tutorial on Forms (Part 4), and several SO threads.

I have a home page which has a form in which the user should be able to enter the name of some basketball player. When they hit submit it should redirect to my other page, the player_stats page, which will show some information about that player. I would ideally also like to have this same form available on the player_stats page itself so that the user can go from player to player without having to go back to the home page in between.

I should add, the name of the app in which all these files live in "desk".

forms.py

from django import forms

class NameForm(forms.Form):
    name = forms.CharField(label='Name', max_length=100)

index.html

<div> HOME PAGE </div>
<form action="{% url 'player_stats' name %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Go"/>
</form>

views.py

def index(request):
template = loader.get_template('desk/index.html')
return HttpResponse(template.render(request))   

def player_stats(request, name):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
    # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # redirect to a new URL:
            name = form.cleaned_data['name']

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    template = loader.get_template('desk/player_stats.html')
    context = get_player_stats_context(tag)

    return HttpResponse(template.render(context, request))

urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<name>([\s\S]+))/player_stats/$', views.player_stats, name='player_stats'),
]

I guess the examples shown in the docs are slightly different from my situation because the template always seems to have some context object provided by the view or the redirect is to a hardcoded url that just happens if the form is valid and the url doesn't depend on what the content of the submitted form was. What am I not getting here?

You should use name given in form.cleaned_data not form.name . So your code should be

return HttpResponseRedirect(reverse('desk:player_stats', 
                       args=(form.cleaned_data['name'],)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM