5

我有一个问题,我成功注册用户 - 但是,我希望用户在注册时登录。这是代表我的注册视图的代码。有关为什么用户没有自动登录的想法?用户注册后Django自动登录(1.4)

注:

  • 用户正在正确注册,他们可以在这个
  • 身份验证后登录(** kwargs)将返回正确的用户
  • 在settings.py我有:

    AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) 
    

谢谢!

def register(request): 
    user_creation_form = UserCreationForm(request.POST or None) 
    if request.method == 'POST' and user_creation_form.is_valid(): 
     u_name = user_creation_form.cleaned_data.get('username') 
     u_pass = user_creation_form.cleaned_data.get('password2') 
     user_creation_form.save() 
     print u_name # Prints correct username 
     print u_pass # Prints correct password 
     user = authenticate(username=u_name, 
          password=u_pass) 
     print 'User: ', user # Prints correct user 
     login(request, user) # Seems to do nothing 
     return HttpResponseRedirect('/book/') # User is not logged in on this page 
    c = RequestContext(request, {'form': user_creation_form}) 
    return render_to_response('register.html', c) 

回答

3

啊!我想到了。如果任何人有这个问题,如果你手动调用它,从django.contrib.auth导入登录 - 我正在导入视图。注释掉的代码代表了我的情况的不良输入。

# from django.contrib.auth.views import login 
from django.contrib.auth import authenticate, logout, login 
3

我做这种方式:

u.backend = "django.contrib.auth.backends.ModelBackend" 
login(request, u) 
+0

谢谢!这很好。 – zallarak 2013-03-04 00:54:31

+0

我也使用 – nemesisdesign 2014-03-11 18:24:28

1

这里基于类的观点是,对我工作的代码(Django的1.7)

from django.contrib.auth import authenticate, login 
from django.contrib.auth.forms import UserCreationForm 
from django.views.generic import FormView 

class SignUp(FormView): 
    template_name = 'signup.html' 
    form_class = UserCreationForm 
    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 super(SignUp, self).form_valid(form) 
+0

你的'form_class'应该是'UserCreationForm'而不是'UserCreateForm'我想。 – blissini 2015-11-18 10:08:55

+0

感谢@blissini改变了它 – colins44 2015-11-18 15:52:14

+0

因为我需要一个解决方案,正如@Patrick指出在这个线程的评论:http://stackoverflow.com/questions/3222549/how-to-automatically-login-a-user在注册后的django中,使用'authenticate(username = form.cleaned_data ['username'],password = form.cleaned_data ['password1'])'进行身份验证甚至更好,以防由于某种原因在验证期间。 – blissini 2015-11-18 22:22:53