Django User Creation成功,但authenticate()返回None

时间:2016-03-29 23:39:03

标签: django authentication

我写了一个自定义页面来创建一个新用户。用户成功创建,但是如果我尝试使用正确的凭据登录,则身份验证将返回无。

如果我进入Django Admin,我可以为刚刚创建的用户创建一个新密码,然后登录成功。任何想法?

创建用户功能:

def create_account(request):
if request.method == "POST":
    # Default User Fields
    username = request.POST['username']
    password = request.POST['password']
    email = request.POST['email']
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']


    try:
        user = User.objects.create_user(username,email,password,first_name=first_name, last_name=last_name)
        user.save()
        user_profile = models.User_Profile.objects.create_user_profile(user)
        user_profile.save()
        response = {'success': True}
        return HttpResponse(json.dumps(response))
    except Exception, e:
        response = {'success': False}
        return HttpResponse(json.dumps(response))

登录功能:

def site_login(request):
#TODO: GET THIS WORKING
if request.method == "POST":
    user = authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        if user.is_active:
            login(request, user)
            response = {'success':True}
            return HttpResponse(json.dumps(response))
        else:
            response = {'success':False,'message':'Account has been disabled.'}
            return HttpResponse(json.dumps(response))
    else:
        response = {'success':False,'message':'Invalid username or password.'}
        return HttpResponse(json.dumps(response))

1 个答案:

答案 0 :(得分:0)

创建用户(https://docs.djangoproject.com/en/1.9/ref/contrib/auth/#django.contrib.auth.models.User.set_password)时需要使用set_password。尝试做:

def create_account(request):
    if request.method == "POST":
        # Default User Fields
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')

        try:
            # illustrating it out for you
            user = User()
            user.username = username
            user.email = email
            user.set_password(password)
            user.first_name = first_name
            user.last_name = last_name
            user.save()
            user_profile = models.User_Profile.objects.create_user_profile(user)
            user_profile.save()
            response = {'success': True}
            return HttpResponse(json.dumps(response))
        except Exception, e:
            response = {'success': False}
            return HttpResponse(json.dumps(response))