简体   繁体   中英

Django redirecting to another view with a bound form

I am using Python 2.7 , Django 1.3.1 .

I am trying to implement a sign in functionality that can be called from arbitrary page and redirects to the same page without any code duplication. The current way that I have is that I have two views: one for the homepage and one for sign in. I want to be able redirect from sign_in view to the home view with a bound form . The main problem is that when the user enters incorrect data (eg wrong password) I want to redirect to the same page but want to send the context of the original form. I want to be able to do this without explicitly calling the view function since I want to be able to do it from arbitrary page. How do I do this? My current attempts always return an unbound form in case the data is invalid.

My current code is (simplfied):

urls.py

urlpatterns = patterns('myapp.views',
    url(r'^$', 'index', name='home'),
    url(r'sign_in/^$', 'signin', name='sign_in')
)

views.py

def index(request, loginForm=LoginForm)
    extra_context = dict()
    extra_context['login_form'] = loginForm
    return direct_to_template(request, 'home.html', extra_context=extra_context)

def signin(request)
    if request.method == 'POST':
        login_form = LoginForm(request.POST, request.FILES)
        if login_form.is_valid():
            # login user 
        redirect_view = reverse('home')
        return redirect(redirect_view, kwargs={'loginForm': login_form})
        # I also tried:  
        # return redirect(redirect_view, loginForm=login_form)
        # what works is:
        # return index(request, loginForm = login_form)

home.html

<form action="{% url sign_in %}" method="post">
    {{ form.as_p }}
</form>

Not with reverse. Reverse gets you a path /my-homepage/

The django paradigm for this is to use a hidden "next" variable set to the initial page.

#In your template
<input type="hidden" value="{{ request.path }}" name="next" />

Then, on success return an HttpResponseRedirect to next:

     if login_form.is_valid():
         # login user 
         return HttpResponseRedirect(form.cleaned_data['next'])

This is durable, because if there is an issue, you display a form with errors on the /account/login/ page with the hidden next variable and the user still gets back to where they were.

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