简体   繁体   English

如何在 Django 中启用非超级用户从前端登录?

[英]How to enable non-superusers login from front end in Django?

I've created a view for login but Django only authenticates the superuser.我为登录创建了一个视图,但 Django 仅对超级用户进行身份验证。 The non-superusers are not able to log in. I only want non-superuser to login from the frontend非超级用户无法登录。我只希望非超级用户从前端登录

def logingin(request):
    if request.method == 'POST':
        username = request.POST.get('username','')
        password = request.POST.get('password','')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/')
        else:
            return redirect('/signup')

    return render(request, 'login.html')

Can any tell me what modifications I need to do in my codes?谁能告诉我我需要在我的代码中做哪些修改?

You didn't show us how you are crearting the new user (the one that cant login).您没有向我们展示您如何创建新用户(无法登录的用户)。

You can go to admin panel and check if your password is properly hashed:您可以 go 到管理面板并检查您的密码是否正确散列: 查看密码是否正确散列

If its not, you will se a message:如果不是,您将看到一条消息:

"django Invalid password format or unknown hashing algorithm"

By default, saving form does not hash your password properly.默认情况下,保存表单不会正确地输入您的密码。 To properly create a user do something like:要正确创建用户,请执行以下操作:

user = form.save(commmit=False)
user.set_password(user.password)
user.save()

Then you're fine:)那你就好了:)

your is_active flag of non-superusers must be set to false您的非超级用户的is_active标志必须设置为 false

https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.is_active https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.is_active

below is the excerpt下面是摘录

This doesn't necessarily control whether or not the user can log in. Authentication backends aren't required to check for the is_active flag but the default backend (ModelBackend) and the RemoteUserBackend do.这不一定控制用户是否可以登录。身份验证后端不需要检查 is_active 标志,但默认后端 (ModelBackend) 和 RemoteUserBackend 可以。 You can use AllowAllUsersModelBackend or AllowAllUsersRemoteUserBackend if you want to allow inactive users to login.如果要允许非活动用户登录,可以使用 AllowAllUsersModelBackend 或 AllowAllUsersRemoteUserBackend。 In this case, you'll also want to customize the AuthenticationForm used by the LoginView as it rejects inactive users.在这种情况下,您还需要自定义 LoginView 使用的 AuthenticationForm,因为它拒绝非活动用户。 Be aware that the permission-checking methods such as has_perm() and the authentication in the Django admin all return False for inactive users.请注意,诸如 has_perm() 之类的权限检查方法和 Django 管理员中的身份验证对于非活动用户都返回 False。

https://stackoverflow.com/a/18209379/3053228 https://stackoverflow.com/a/18209379/3053228

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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