我正在尝试检查当前登录的用户是否是管理员,然后允许他们访问管理页面,否则返回主页。这是我的观点.pyfrom django.shortcuts import render, redirectfrom django.http import HttpResponsefrom django.contrib.auth import login, logout, authenticatefrom django.contrib import messagesfrom teacher.models import usersdef 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.pyclass 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")我尝试过使用不同的查询方法。但我最终收到错误页面,因为“用户匹配查询不存在”。它也不检查用户是否登录。即使用户未登录,它也会返回到管理页面。
2 回答
慕勒3428872
TA贡献1848条经验 获得超6个赞
你搜索过装饰器吗?看看在我的 django 应用程序上检查管理员登录
对于仪表板访问检查Django 登录装饰器,如果未登录,您可以将用户重定向回登录页面。
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
对于第二个“用户匹配查询不存在”。检查您是否有数据库表。确保已运行迁移并使用 Try Exception
try:
user = users.objects.get(category = 'admin')
if user:
return render(request, 'main/admin.html')
except Exception as e:
return render(request, 'main/home.html')
添加回答
举报
0/150
提交
取消