将Angular移植到DJango Web(1.0)样式:从DJango Temp调用函数

2024-09-30 22:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django的新手,我需要完成的任务是将AngularJs移植到一个老式的Web1.0Django应用程序(对于较旧的浏览器)。我正在处理一个未知的函数,它与angular中的$scope相关。我不知道如何在Django中复制这种逻辑。你知道吗

例如(角度):

<div ng-show="isAuthorizedAs('Administrator')"></div>

然后在控制器中:

$scope.isAuthorizedAs = function(functionalRole) {
     if($scope.user.role == 'basic'){
        if(functionalRole == 'basic') return true
     }
     else if($scope.user.role == 'advanced'){
        if(functionalRole == 'basic') return true
        if(functionalRole == 'advanced') return true
     }
     else if($scope.user.role == 'administrator'){
        if(functionalRole == 'basic') return true
        if(functionalRole == 'advanced') return true
        if(functionalRole == 'administrator') return true
     }

     return false
}

要点是控制器要么有复杂的逻辑(在一个模型或多个模型上工作)要么有特殊的格式。我意识到这些可能是非最佳用例,上面的javascript函数还有很多需要改进的地方——但这两个目标都在我的直接执行路径中。你知道吗

我的目标是在一周内构建出这个功能,并且不希望与AngularJs模板/应用程序有太大的偏离。因此,我愿意承认一个非最佳的解决方案,为我的交付-然后重新考虑在未来的日期。你知道吗

谢谢


Tags: django函数divtrue应用程序returnifbasic
1条回答
网友
1楼 · 发布于 2024-09-30 22:19:37

我不太清楚你的问题是什么。你要找的是检查登录的用户是否是管理员,如果是,呈现模板的一部分。这是你在学习Django的过程中学到的最基本的东西之一。不过,下面是实现上述场景的方法。你知道吗

我不知道你的用户模型是什么样子,因为你没有提到它。所以我假设您的用户模型有一个名为role的字段,可以设置为basicadvancedadministrator。现在,当您登录到Django时,当前登录的用户对象在模板中的变量user中可用,前提是您在settings.py中的django.contrib.auth.context_processors.auth设置中有TEMPLATE_CONTEXT_PROCESSORS。你知道吗

在模板里你可以这样做-

{% if user.role == 'administrator' %}
<div class="secret_div">
    Super Secret Information Here
</div>
{% endif %}

如果您的用户模型没有任何这样的字段,并且您有其他一些方法来检查用户是否是admin,那么您可以通过子类化默认的User类或创建自己的用户模型来向用户对象添加方法。你知道吗

class User(AbstractBaseUser, PermissionsMixin):
    """
    Username, password and email are required. Other fields are optional.
    """
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and '
                    '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
        ])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), unique=True)

    # more fields here 

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_role(self):
        """
        Returns the role of the user
        """
        return magic_method_to_check_role(self)

那就像你做这件事之前一样

{% if user.get_role == 'administrator' %}
<div class="secret_div">
    Super Secret Information Here
</div>
{% endif %}

相关问题 更多 >