我正在尝试检查当前登录的用户是否是管理员,然后允许他们访问管理页面,否则返回主页。
这是我的观点.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from teacher.models import users
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
if user is not None:
login(request, user)
print (user)
messages.success(request, "You have successfully Logged In.")
return redirect('index')
else:
messages.error(request, "You have entered invalid credentials. Please try again")
return redirect('login')
else:
return render(request, 'main/login.html')
def admin(request):
user = users.objects.get(category = 'admin')
if user:
return render(request, 'main/admin.html')
elif Exception:
return render(request, 'main/home.html')
这是我的 models.py
class users(models.Model):
_id = models.AutoField
name = models.CharField(max_length = 100)
username = models.CharField(max_length = 100)
email = models.EmailField(max_length=254)
hpassword = models.CharField(max_length = 255)
category = models.CharField(max_length=50, default= "teacher")
我尝试过使用不同的查询方法。但我最终收到错误页面,因为“用户匹配查询不存在”。它也不检查用户是否登录。即使用户未登录,它也会返回到管理页面。
慕勒3428872
繁星coding
相关分类