Django, return to previous page after post form

On my webpage, I have a form populated with data after some ajax requests. For example, when a user selects an item from a list, a simple ajax request is sent to the database, which has been selected (but not yet confirmed). Then the list on the web page is reloaded using the apex ajax request (only the list, not the whole page) to select a new list of elements.

I think this is a more or less classic basket implementation.

However, when the user clicks submit (the classic POST submit form rather than ajax POST for some implementation reasons) to confirm the entire list, I would like to return to the current page. (Current page is changing) Is this possible? I am using django.

Thank.

+5
source share
3 answers

You can specify the nextGET parameter when submitting the form, similar to the django.contrib.auth method login():

https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login :

<form action="/url/to/post/form/?next={{ some_variable }}">

where the variable may simply be the current URL (taken from the request) or the generated URL. In the view processing the form, just check the parameter nextand redirect accordingly:

from django.shortcuts import redirect
if 'next' in request.GET:
    return redirect(request.GET['next'])
+11
source

You may be able to use the Post / Redirect / Get Design (PRG) template. For more general information about Post / Redirect / Get, see the following: http://en.wikipedia.org/wiki/Post/Redirect/Get There are interesting process diagrams there.

PRG :

# urls.py
urlpatterns = patterns('',
    url(r'^/$', views.my_view, name='named_url'),
)

# forms.py
class MyForm(forms.Form):
    pass # the form

# views.py
def my_view(request, template_name='template.html'):
    """ Example PostRedirectGet 
    This example uses a request context, but isn't 
    necessary for the PRG
    """
    if request.POST:
        form = MyForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                # on success, the request is redirected as a GET
                return HttpResponseRedirect(reverse('named_url'))
            except:
                pass # handling can go here
    else:
        form = MyForm()

    return render_to_response(template_name, {
        'form':form
    }, context_instance=RequestContext(request))

- GET, reverse args kwargs. , url_pattern , , .

, ( ). , .

+1

The current page is a very vague term, but I assume that you want the page to link to the form page, this is usually (not always) stored in the HTTP_REFERRER header of the request itself. You can try to get this from the request and do a redirect.

0
source

All Articles