简体   繁体   中英

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. 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.

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:

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:

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 .

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.

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 . So, with the current code when you make superuser through python manage.py createsuperuser and then you authenticate, so it will work.

You should use @login_required(login_url='login') instead of @login_required(redirect_field_name='login') .

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