سؤال

I'm getting a form resubmission error when I refresh a page or submit back button..to prevent this after the post request, Im redirecting it to a new page that will display the actual page...when I do that...I get the below error after I click the submit button on the mainpge.html

Error: NoReverseMatch at /startpage/

Reverse for 'testpage' with arguments '()' and keyword arguments '{}' not found.

views.py

from django.shortcuts import render_to_response, redirect
from django.views.decorators.csrf import csrf_exempt
from django.template import Context, RequestContext
@csrf_exempt
def mainpage(request):
    return render_to_response('mainpage.html')

@csrf_exempt
def startpage(request):
    if request.method == 'POST':
       print 'post', request.POST['username']
    else:
       print 'get', request.GET['username']
    variables = RequestContext(request,{'username':request.POST['username'],
           'password':request.POST['password']})
    #return render_to_response('startpage.html',variables)
    return redirect('testpage')

def testpage(request):
    variables = {}
    return render_to_response('startpage.html',variables)                                                           

urls.py

urlpatterns = patterns('',
    url(r'^$',mainpage),
    url(r'^startpage',startpage),

startpage.html

<html>
<head>
<head>
</head>
<body>
<input type="submit" id="test1" value="mainpage">
This is the StartPage
Entered user name ==   {{username}}
Entered password  == {{password}}
</body>
</html>

mainpage.html

<html>
<head>
</head>
<body>
This is the body
<form method="post" action="/startpage/">{% csrf_token %}
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Sign with password">
</form>
</body>
</html>
هل كانت مفيدة؟

المحلول

According to the docs, redirect takes either of the following three:

  1. A model: the model’s get_absolute_url() function will be called.
  2. A view name, possibly with arguments: urlresolvers.reverse will be used to reverse-resolve the name.
  3. An absolute or relative URL, which will be used as-is for the redirect location.

By passing a string not started with a protocol and doesn't contain slashes, the argument is recognised as a name, and is passed into reverse.

The wording is maybe a bit misleading here. reverse looks up a view by its URL pattern name, so when the document says that it takes a view name it actually means the name of a URL pattern that points to a view, not the name of the view itself. Since reverse looks in your urlpatterns (in urls.py) for URL patterns, you need to add testpage into it so that it can be found by reverse:

url(r'^whatever/$', testpage, name='testpage')

Obviously you can put any pattern you wish in the first argument, and need to import the view function for the second argument. The name part is what reverse uses to look up the URL.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top