def login(request, template_name='accounts/login.html', extra_context={}): """ contrib.auth.views.login, but with a few added benefits: extra_context and it redirects to settings.LOGIN_REDIRECT_URL if user is already logged in. """ if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): redirect_to = get_redirect_url(request, redirect_field_name='next', fallback=settings.LOGIN_REDIRECT_URL) auth_raw_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: form = AuthenticationForm(request) request.session.set_test_cookie() if Site._meta.installed: current_site = Site.objects.get_current() else: current_site = RequestSite(request) context = { 'form': form, 'site': current_site, 'site_name': current_site.name } context.update(extra_context) return direct_to_template(request, template_name, context)
def register(request, template_name='accounts/register.html'): if request.method == 'POST': form = UserCreationForm(data=request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get("username") password = form.cleaned_data.get("password1") user = authenticate(username=username, password=password) auth_raw_login(request, user) messages.success(request, 'Registration successful.') redirect_to = get_redirect_url(request, fallback=settings.REGISTER_REDIRECT_URL) return HttpResponseRedirect(redirect_to) else: # request.method == 'GET' form = UserCreationForm() return direct_to_template(request, template_name, locals())