简体   繁体   中英

Django: authenticate the user

I have the following code:

# creating user:

def create_user(request):
    if request.method == 'POST':
        user_info = forms.UserInfoForm(request.POST)
        if user_info.is_valid():
            cleaned_info = user_info.cleaned_data
            User.objects.create_user(username=cleaned_info['username'], password=cleaned_info['password'])
   render(.......)

This works. I can check the auth_user and I see the username and password along with all the other fields created and added.

Now, I try to authenticate the user with the following code after creating user with username='testcase' and password='test': using above code.

# Authenticate User

def get_entry(request):
    if request.method == 'POST':
        user = authenticate(username='testcase', password='test')
        if user:
            .........

The user is always returned as none. What is going on? I am running django 1.10.2.

Update:

I can see the user created by create_user function when I log in admin. The status was not staff(as it was supposed to be). I changed that to staff to see if that was causing problem but still the get_entry method yields none for user. It is frustrating. I don't really know what I am doing wrong.

Save the user in one var, and then call user.save() because User can't call the method save() try it:

def create_user(request):
        if request.method == 'POST':
            user_info = forms.UserInfoForm(request.POST)
            if user_info.is_valid():
                cleaned_info = user_info.cleaned_data
                user = User.objects.create_user(username=cleaned_info['username'], password=cleaned_info['password'])
                user.save()
       render(.......)

Then you need to call auth.authenticate in your function get_entry:

def get_entry(request):
    if request.method == 'POST':
        user = auth.authenticate(username='testcase', password='test')
        if user:
            .........

Your code seems to be correct.

The problem might be in the way the params are being passed to your create_user view (Param passing in get_entry view highly unlikely to be a problem since the params username and password are hard-coded).

Try printing out username and password before passing them to User.objects.create_user() , since it's possible that the password field is not being saved properly and/or empty password is being passed, and Django might be creating a hash for the empty password.

PS: This is just a speculation, need your response over this for further diagnosis of the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM