在Django Rest Framework中保存用户时添加权限

时间:2016-09-27 21:32:06

标签: django django-rest-framework django-permissions

我正在创建一个<form class="form-horizontal" method="post" action=""> <strong>Login: </strong><input type="text" id="username" name="username" placeholder="Username"> <input type="password" id="password" name="password" placeholder="Password"> <input type="submit" name="submit" value="Login"> </form>对象的实例。创建本身是一个标准的User调用,并且工作正常 - 用户已创建。之后,我正在尝试为他或她添加一些权限:

User.objects.create_user

正如您所看到的,在最后一行我正在检查是否为用户分配了适当的权限,而上面几行我正在检查权限是否为for name in ('view_restaurant', 'change_restaurant', 'delete_restaurant', 'view_meal', 'add_meal', 'change_meal', 'delete_meal', 'view_order', 'delete_order', 'view_historicalorder', 'add_historicalorder', 'change_historicalorder', 'view_orderitem', 'view_historicalorderitem', 'view_restaurantemployee', 'add_restaurantemployee', 'change_restaurantemployee', 'delete_restaurantemployee'): permission = Permission.objects.get(codename=name) print(permission is None) user.user_permissions.add(permission) user.save() print(user.has_perm(permission)) 。结果是权限对象永远不会为none,但None调用始终返回false。我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

您正在正确调用has_perm。它需要这种格式的字符串

codenames = 'view_restaurant', 'change_restaurant', ...
perms = Permission.objects.filter(codename__in=codenames)
user.user_permissions.add(*perms)

顺便说一下,我可以建议简化代码:

myFunction: function(some args, myBoolean) {
  var deffered = q.defer()
  if(myBool) {
    module.exports.mySecondfunction(args, false, null)
  } else {
    return module.exports.mySecondfunction(args, true, deffered)
},

mySecondFunction: function(some args, myBoolean, myPromise) {
  //Some work here
  if(myBoolean) {
    //Some work
    promise.resolve();
    return myPromise.promise
  }
}

anotherFunction: function(some args) {
  //some work
  if (something) {
    myFunction(some args, true)
  } else {
    myFunction(some args, false).then((data) => {
      //do stuff
    }
  }
}