使用Django的“规则" CBV似乎不起作用 [英] Using Django "rules" with CBVs doesn't seem to work
问题描述
每个餐厅可以有多个经理.
Each restaurant can have multiple managers.
class Restaurant(models.Model):
...
managers = models.ManyToManyField(User, related_name='restaurants_which_they_manage')
只有餐厅经理可以更改餐厅列表.我正在使用 django-rules 来强制执行此操作.我有一个谓词,它创建了一个很好的冗长的"is_restaurant_manager"参考:
Only restaurant managers can change a restaurant listing. I'm using django-rules to enforce this. I've got a predicate that creates a nice verbose "is_restaurant_manager" reference :
@rules.predicate
def is_restaurant_manager(user, restaurant):
return user in restaurant.managers.all()
这是许可:
rules.add_perm('restaurants.change_restaurant', is_restaurant_manager)
最后,这是我的观点:
class RestaurantChange(PermissionRequiredMixin, UpdateView):
model = Restaurant
permission_required = 'restaurants.change_restaurant'
fields = ['name', 'description', ]
我有两个测试.
测试A检查权限是否正常运行:
Test A checks that the permission works properly :
self.assertEqual(rules.has_perm('restaurants.change_restaurant', self.user, self.restaurant), True)
第一个测试成功通过.
测试B尝试使用有效用户访问网址:
Test B attempts to access the url with a valid user :
url = reverse('restaurants__restaurant_change', kwargs={'pk': self.restaurant.key,})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
测试B失败,因为我得到了重定向.如果我尝试通过浏览器访问URL,也会发生这种情况.重定向进入登录过程,就好像用户没有访问该视图的权限.
Test B fails, as I get a redirection. This also happens if I try to access the url via the browser. The redirection goes to the login process, as though the user didn't have permission to access the view.
我的代码有什么问题?
推荐答案
我在玩django-rules,看看它是否适合项目的需求,并遇到了您在django-rules上添加的问题.
I was playing around with django-rules to see if it suits the needs of a project and run into the issue you added on django-rules.
在测试中添加pdb跟踪并完成设置后,我注意到以下内容:
After adding a pdb trace in the tests and going through your settings I noticed the following:
第二个链接是一个分配,它覆盖了先前分配中设置的身份验证后端.
The second link is an assignment, overriding authentication backend set in the previous assignments.
通过将'rules.permissions.ObjectPermissionBackend'
添加到第二组后端中,测试将通过且没有错误.
By adding the 'rules.permissions.ObjectPermissionBackend'
to the second set of backends, the tests pass without error.
我在github上发出了拉取请求以解决此问题: https://github.com /tavolia/Tavolia/pull/5
I made a pull request on github to solve this issue: https://github.com/tavolia/Tavolia/pull/5
干杯!
这篇关于使用Django的“规则" CBV似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!