1

There's lots of documentation about Django and the reverse() method. I can't seem to locate my exact problem. Suppose I have two urlconfs like this:

url(r'ParentLists/$', main_page, name = "main_page"),
url(r'ParentLists/(?P<grade_level>.+)/$', foo, name = "foo")

and the two corresponding views like this:

def main_page(request):

    if request.method == 'POST':
        grade_level = request.POST['grade_picked']
        return HttpResponseRedirect(reverse('foo', args = (grade_level,)))

    else:
        return render(request, 'index.html', context = {'grade_list' : grade_list})

def foo(request, grade_level):

    grade_level = request.POST['grade_picked']

    parent_list = # get stuff from database
    emails      = # get stuff from database

    return render(request, 'list.html', context = {'grade_list' : grade_list, 'parent_list' : parent_list}) 

Here, list.html just extends my base template index.html, which contains a drop down box with grade levels. When the user goes to /ParentLists, the main_page view renders index.html with the drop down box as it should.

When the user picks a grade level from the drop down box (say 5th Grade), the template does a form submit, and main_page once again executes - but this time the POST branch runs and the HttpResponseRedirect takes the user to /ParentLists/05. This simply results in an HTML table pertaining to grade 5 being displayed below the drop down box.

The problem is, when the user now selects say 10th Grade, the table updates to show the grade 10 content, but the URL displayed is still /ParentLists/05. I want it to be /ParentLists/10.

Clearly, after the first selection, the main_page view never executes again. Only foo does...and so the HttpResponseRedirect never gets called. How should I reorganize this to get what I'm looking for? Thanks in advance!

4

2 回答 2

2

正如您正确提到的,您永远不会从 foo() 重定向到 foo()。

所以解决这个问题的简单方法是在 main_page() 视图中添加类似的代码:

def foo(request, grade_level):

    if request.method == 'POST':
        grade_level = request.POST['grade_picked']
        return HttpResponseRedirect(reverse('foo', args = (grade_level,)))
    else:
        parent_list = # get stuff from database
        emails      = # get stuff from database

        return render(request, 'list.html', context = {'grade_list' : grade_list, 'parent_list' : parent_list})

请注意,我删除grade_level = request.POST['grade_picked']是因为 Nagkumar Arkalgud 正确地说它是过度的。

此外,您可以使用可能不太容易编码的快捷方式来代替HttpResponseRedirectand的组合:reverseredirect

from django.shortcuts redirect
...
return redirect('foo', grade_level=grade_level) 
于 2016-12-14T05:48:22.497 回答
0

我建议你使用 kwargs 而不是 args。使用视图的正确方法是:

your_url = reverse("<view_name>", kwargs={"<key>": "<value>"})

前任:

return HttpResponseRedirect(reverse('foo', kwargs={"grade_level": grade_level}))

此外,您使用 URL 而不是 POST 值将“grade_level”发送到您的视图 foo。我会删除该行:

grade_level = request.POST['grade_picked']

因为您将覆盖从 url 发送到方法的grade_level。

于 2016-12-14T02:53:44.820 回答