This is what I am currently using for registration:
def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() messages.info(request, "Thanks for registering. Please login to continue.") return HttpResponseRedirect("/dashboard/") else: form = UserCreationForm() return render_to_response("accounts/register.html", { 'form': form, }, context_instance=RequestContext(request)) Is it possible not to require the user to login manually after creating an account, but rather simply to log them in automatically? Thanks.
edit: I had tried the login() function without success. I believe the problem is that AUTHENTICATION_BACKENDS was not set.
Check the Logged in User in Views in Django We can use request. user. is_authenticated to check if the user is logged in or not. If the user is logged in, it will return True .
from django. contrib. auth import authenticate user = authenticate(username='john', password='secret') if user is not None: if user. is_active: print "You provided a correct username and password!" else: print "Your account has been disabled!" else: print "Your username and password were incorrect."
Using the authenticate() and login() functions:
from django.contrib.auth import authenticate, login def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() messages.info(request, "Thanks for registering. You are now logged in.") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return HttpResponseRedirect("/dashboard/")
for class based views here was the code that worked for me (originally Django 1.7, updated for 2.1)
from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.views.generic import FormView class SignUp(FormView): template_name = 'signup.html' form_class = UserCreateForm success_url='/account' def form_valid(self, form): #save the new user first form.save() #get the username and password username = self.request.POST['username'] password = self.request.POST['password1'] #authenticate user then login user = authenticate(username=username, password=password) login(self.request, user) return HttpResponseRedirect(self.get_success_url)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With