简体   繁体   English

@login_required 装饰在 Django 中不起作用(用户未通过身份验证?)

[英]The @login_required decoration is not working in Django (user not authenticated?)

I am trying to set up a login page and I am trying to use the @login_required decoration.我正在尝试设置登录页面,并且正在尝试使用@login_required装饰。 However, whenever I try and log in with valid credentials I am re-directed to the 'login' page (set to re-direct unauthenticated users).但是,每当我尝试使用有效凭据登录时,我都会被重定向到“登录”页面(设置为重定向未经身份验证的用户)。 I am not sure if the problem is in the @login_required decoration or perhaps the login() function is not authenticating the user.我不确定问题出在 @login_required 装饰中,还是 login() 函数未对用户进行身份验证。

Here is my code for the register form:这是我的注册表单代码:

class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    confirm_password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password']

code for login function in views.py: views.py 中登录功能的代码:

def login_user(request):
if request.method =="GET":
    return render(request, "main/login.html", {})
else:
    username = escape(request.POST['userfield'])
    password = escape(request.POST['passfield'])
    
    try:
        user = User.objects.get(username=username)
    except:
        user = None
    
    if user is None:

        try:
            user = User.objects.get(email=username)
        except:
            user = None

            if user is None:
                messages.info(request, "*Sorry, that username or email does not exist")
                return redirect('login')
    
    pword = user.password

    if check_password(password, pword):
        login(request, user)
        return redirect('homepage')
        
    else:
        messages.info(request, '*Sorry, that was an incorrect password')
        return redirect('login')

my model for User in models.py:我在models.py中的用户模型:

class User(models.Model):
   first_name = models.CharField(max_length=100)
   last_name = models.CharField(max_length=100)
   username = models.CharField(max_length=100)
   email = models.EmailField(unique=True)
   password = models.CharField(max_length=100)
   admin = models.BooleanField(default=False)
   last_login = models.DateTimeField(null=True, blank=True)

and my function to reach the 'homepage' after login:以及我在登录后访问“主页”的功能:

@login_required(redirect_field_name='login')
def homepage(request):
   return render(request, "main/homepage.html", {})

You need to correctly authenticate the user before logging in.您需要在登录前正确验证用户身份。

from django.contrib.auth import authenticate, login
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
    login(request, user)

More information in the documentation 文档中的更多信息

When you make custom user model, so you should always use AbstractBaseUser .当您制作自定义用户模型时,您应该始终使用AbstractBaseUser

Note: It's also not a good practice to name same your models, django already has User model in the django.contrib.auth , so change its name. Note:将模型命名为相同也不是一个好习惯,django 已经在django.contrib.auth中有User模型,因此请更改其名称。

So, you haven't specified the custom user model, so you should not able to authenticate, as by default authentication model is User which is at django.contrib.auth .因此,您尚未指定自定义用户模型,因此您不应该进行身份验证,因为默认身份验证模型是User ,位于django.contrib.auth So, with the current code when you make superuser through python manage.py createsuperuser and then you authenticate, so it will work.因此,当您通过python manage.py createsuperuser创建超级用户然后进行身份验证时,使用当前代码,这样它就可以工作了。

You should use @login_required(login_url='login') instead of @login_required(redirect_field_name='login') .您应该使用@login_required(login_url='login')而不是@login_required(redirect_field_name='login')

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

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