Reputation: 22747
I have a registration form and if the registration form is filled in correctly and is valid, I want to automatically log the user in. The login view is at the URL
/login/
and this is the login view which that URL is linked to (it's the generic login view):
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
if request.method == "POST":
form = authentication_form(data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
# Okay, security check complete. Log the user in.
auth_login(request, form.get_user())
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form(request)
request.session.set_test_cookie()
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
Now, the view which handles registration is:
def registrationView(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email']
)
return HttpResponseRedirect('/login/')
Now, when I redirect to
/login/
in the registration view, is it possible for me to send the username and password as "POST" information so that when it reaches the login view
if request.method == "POST":
evaluates to true?
Upvotes: 0
Views: 2033
Reputation: 3813
I think that, instead of trying to do such magic, you should set the current user to your session.
def registrationView(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
login(request, user)
return HttpResponseRedirect('...')
Take a look at https://docs.djangoproject.com/en/1.5/topics/auth/default/#django.contrib.auth.login
Upvotes: 2