用户未在Django中进行身份验证?

时间:2020-11-03 05:38:10

标签: django authentication

我正在使用Django版本:3.0.2。学生注册正在运行,并且用户已成功保存到数据库。问题是登录后显示“用户”,但重定向到其他页面后未显示“用户”。请任何人解决我的问题吗?

views.py:

from django.contrib.auth.models import User, Group, auth

def studentregistration(request):
    if request.method == 'POST':
        form = StudentRegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['user_name']
            password = form.cleaned_data['password']
            confirmpassword = form.cleaned_data['confirm_password']
            email = form.cleaned_data['email']

            if password == confirmpassword:
                if User.objects.filter(username=username).exists():
                    messages.error(request,'user already exists please login')
                    return render(request, 'login.html')
                elif User.objects.filter(email=email).exists():
                    messages.error(request, 'email already registered please login')
                    return render(request, 'login.html')
                else:
                    user=User.objects.create_user(username=username, password=password, email=email)
                    user.save()
                    messages.success(request, "Successfully registered, Please login")
                    return render(request, 'login.html')
            else:
                messages.error(request, 'password and confirmation password do not match')
                return render(request, 'studentregistration.html')
                #return HttpResponseRedirect('studentregistration.html')
    else:
        form = StudentRegisterForm()
    return render(request, 'studentregistration.html', {'form': form})


def login(request):
    if request.method == 'POST':
        username = request.POST.get('user_name', '')
        password = request.POST.get('password', '')
        user=auth.authenticate(username=username,password=password)
    
        if user is not None:
            auth.login(request, user)
            return HttpResponseRedirect('exam_pattern')
        else:
            messages.error(request,'invalid credentials')
            return render(request, 'login.html')
    else:
      
        return render(request,'login.html')

在这里,我是经过认证的用户,但显示render_questions中的用户为空。

def render_questions(request):
    
    if not request.user.is_authenticated:
       return render(request, 'login.html')
    else:
        global exam_session
        exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
        
        questions = Questions.objects.all()
        return render(request, 'report.html', {'ques': questions})


After log in it is showing user: user is gopi14
[2020-11-03 06:18:19 +0000] [31827] [DEBUG] GET /exam_pattern
[2020-11-03 06:18:21 +0000] [31827] [DEBUG] POST /report
after redirect to report it is showing none

user in render_questions is

0 个答案:

没有答案