5

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

笔记:

  • 用户已正确注册,他们可以在此之后登录
  • authenticate(**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)
4

3 回答 3

3

啊! 我想到了。如果有人遇到这个问题,如果您手动调用它,请从 django.contrib.auth 导入登录名 - 我正在导入视图。注释掉的代码代表我的情况的错误导入。

# from django.contrib.auth.views import login
from django.contrib.auth import authenticate, logout, login
于 2013-03-04T00:46:06.177 回答
3

我这样做:

u.backend = "django.contrib.auth.backends.ModelBackend"
login(request, u)
于 2013-03-04T00:48:36.380 回答
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)
于 2015-03-10T21:49:16.117 回答