67👍
✅
There is no other way than “programmatically”. Of course, this is documented.
from django.contrib.auth import authenticate, login
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
7👍
Alsways be careful when programmatically logging users in, you might get the error ´user has no attribute "backend"
. You have to set the backend too if that has no happened previously. Project that uses this and some sample code:
def splash_register(request):
if request.session.get('beta'):
if request.method=='POST':
userform=MyUserCreationForm(request.POST)
if userform.is_valid():
#username of <30 char is required by Django User model. I'm storing username as a hash of user email
user=userform.save(commit=False)
user.username=hash(user.email)
user.backend='django.contrib.auth.backends.ModelBackend'
user.save()
username=user.username
password=str(userform.cleaned_data['password'])
auth.login(request, user)
request.session['first_visit']=True
return HttpResponseRedirect("/")
else:
userform=MyUserCreationForm(request.POST)
return render_to_response("website/splash_register.html", {'userform':userform}, context_instance=RequestContext(request))
return render_to_response("website/splash_register.html", context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/splash/')
- [Django]-How to use if/else condition on Django Templates?
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-How would you create a 'manual' django migration?
2👍
The accepted answer definitely works but, I prefer to use the Django built in auth forms, like django.contrib.auth.forms.AuthenticationForm
Here is a snippet that shows the important part
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
try:
form.clean()
except ValidationError:
# handle error
login(request, form.get_user())
The major difference in this approach is that AuthenticationForm.clean
method calls authentication
function for you and checks User.is_active
for you as well.
- [Django]-Simply save file to folder in Django
- [Django]-ImportError: No module named django.core.wsgi Apache + VirtualEnv + AWS + WSGI
- [Django]-TypeError: login() takes 1 positional argument but 2 were given
Source:stackexchange.com