У меня есть 2 страницы входа - login_admin
и login_user
для администратора и обычного пользователя соответственно.
Когда пользователь вводит имя пользователя и пароль на страницах login_admin
и login_user
, он проверяет, является ли пользовательis_staff
- это True
или False
.Если user is_staff = True, то разрешите страницу входа пользователя в систему.
Моя проблема: Пользователь не может войти на страницу администратора, хотя is_staff = True
.Пользователь может войти на страницу обычного пользователя, хотя is_staff = True
.Я не знаю, в чем проблема.
Вот мой код в views.py:
def login_admin(request):
context = {}
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
if request.user.is_staff:
login(request, user)
return redirect('/home/')
else:
context['error'] = "You are authenticated but are not authorized to access this page. Would you like to login to a different account?"
return render(request, 'registration/login.html',context)
else:
context['error'] = "Invalid username or password!"
return render(request, 'registration/login.html',context)
return render(request, 'registration/login.html')
def login_user(request):
context = {}
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
if not request.user.is_staff:
login(request, user)
return redirect('/cust/home/')
else:
context['error'] = "Invalid username or password!"
return render(request, 'registration/custlogin.html',context)
else:
context['error'] = "Invalid username or password!"
return render(request, 'registration/custlogin.html',context)
return render(request, 'registration/custlogin.html')
login.html
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Admin Login Screen</h2>
<a href="{% url 'login_user' %}">Customer Login Page</a>
<form method="post">
{% csrf_token %}
<table cellpadding="10">
<tr>
<td><label for="usename">Username: </label></td>
<td><input type="text" name="username" id="username" required></td>
</tr>
<tr>
<td><label for="password">Password: </label></td>
<td><input type="password" name="password" id="password" required></td>
</tr>
<p style="color:red; font-weight: bold">{{ error }}</p>
</table>
<button type="submit" class="btn btn-primary">Login</button>
</form>
{% endblock %}
url.py
url(r'accounts/login/', customers.views.login_admin,name='login_admin'),
url(r'accounts/custlogin/', customers.views.login_user,name='login_user'),
url(r'accounts/logout/', customers.views.logout_user,name='logout_user'),
ОБНОВЛЕНО:
Я не могу войти на страницу администратора, когда is_staff = True / False, что приведет к ошибке You are authenticated but are not authorized to access this page. Would you like to login to a different account?
, записанной вмой код, но может войти на страницу пользователя, когда is_staff = True / False.Если я удаляю if user.is_staff
, это работает для администратора и обычного пользователя.
urls.py
url(r'^accounts/login/$', customers.views.login_admin,name='login_admin'),
url(r'^accounts/custlogin/$', customers.views.login_user,name='login_user'),
url(r'^accounts/logout/$', customers.views.logout_user,name='logout_user'),
ОБНОВЛЕНО V2:
Я пробовал код, написанный @Rarblackно все равно получаю ошибку: 'QuerySet' object has no attribute 'is_staff'
.
Итак, я изменил код, и он работает.
from django.contrib.auth.models import User
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
user_instance = User.objects.filter(Q(username_exact=username) & Q(is_staff=True))
if user_instance:
login(request, user)
return redirect('/home/')
else:
....