如何解决根据用户类型进行身份验证并授予用户一定的权限但注意正在发生
根据用户类型进行身份验证并授予用户一定的权限。但是注意正在发生。 我尝试根据用户类型限制对网站某些功能的访问。但是当我设置条件时,页面上没有任何反应: 这是我的model.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
user_type_choice = (('1','majstor'),('2','korisnik'))
class CustomKorisnici(AbstractUser):
user_type = models.CharField(max_length=100,blank=True,choices=user_type_choice)
username = models.CharField(max_length=100,unique=True)
last_name = models.CharField(max_length=100)
first_name = models.CharField(max_length=100)
phone_number = models.CharField(max_length=100)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
email = models.EmailField(max_length=100,unique=True)
在设置中,我设置了:AUTH_USER_MODEL。
AUTH_USER_MODEL ='korisnici.CustomKorisnici'
这是我的 login.html 页面。这部分工作正常。
{% extends "nav_footer.html" %}
{% load static %}
{% block content %}
<div class="form-group">
<div class="container">
<div class="form">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button id="btn" class="btn" type="submit">Login</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
**在我的 home.html 页面中,我为用户设置了条件,这是一个问题。 **
{% if user.is_authenticated and user.user_type == "korisnik" %}
<div class="col-md-4">
<a class="nav-link" href="{% url 'post_page' %}">All posts</a>
</div>
{% endif %}
首先我设置一个条件 if user.is_authenticated 并且这工作正常。之后只是为了检查,我添加了一个条件 if user.is_authenticated 和 user.username == 'admin'。当我以管理员身份登录或以用户名 == 'John' 的其他条件登录时,它工作正常并且链接可见。 但是,当我尝试条件 user.user_type == "korisnik" 时,即使我登录 whit User 如何将 user_type 设置为 korisnik,链接也不可见。我不知道我在这里做错了什么。我需要做自定义登录功能还是其他什么
解决方法
存储在数据库中的值是元组的第一个值。元组 ('1','majstor')
的意思是第一个值 '1'
将存储在类型为 'majstor'
的用户的字段中。所以在你的模板中你应该写:
{% if user.is_authenticated and user.user_type == "2" %}
另外为了使检查变得容易,最好的办法是在模型中使用常量。所以你会像这样改变你的模型:
class CustomKorisnici(AbstractUser):
MAJSTOR = '1'
KORISNIK = '2'
USER_TYPE_CHOICE = (
(MAJSTOR,'majstor'),(KORISNIK,'korisnik')
)
user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE)
# rest of the fields etc.
现在在模板检查中会变成:
{% if user.is_authenticated and user.user_type == user.KORISNIK %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。