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 (e.g 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>