gpt4 book ai didi

django-fsm:权限不引发异常

转载 作者:行者123 更新时间:2023-12-04 13:47:16 27 4
gpt4 key购买 nike

我在 django-fsm 中让基于源和目标规则的转换装饰器运行良好(有限状态机)。现在我正在尝试添加权限处理。这看起来很简单,但似乎无论我做什么,转换都会执行,无论用户是否拥有权限。我试过 Django 权限字符串,我试过 lambda ,根据文档。我已经尝试了所有这些:

@transition(field=state, source='prog', target='appr', permission='claims.change_claim')


@transition(field=state, source='prog', target='appr', permission=lambda instance, user: not user.has_perm('claims.change_claim'),)

并且,就像仔细检查,因为 permission应该响应任何返回 True/False 的可调用对象,简单地:
@transition(field=state, source='prog', target='appr', permission=False)
def approve(self):

这应该引发 TransitionNotAllowed访问过渡时的所有用户。但是不 - 即使没有权限的基本用户仍然可以执行转换( claim.approve() )。

为了证明我的权限字符串是正确的:
print(has_transition_perm(claim.approve, request.user))

打印 False。我正在按如下方式进行验证(适用于源/目标):
class ClaimEditForm(forms.ModelForm):
'''
Some users can transition claims through allowable states
'''

def clean_state(self):
state = self.cleaned_data['state']
if state == 'appr':
try:
self.instance.approve()
except TransitionNotAllowed:
raise forms.ValidationError("Claim could not be approved")
return state

class Meta:
model = Claim
fields = (
'state',
)

View 处理程序是标准的:
if request.method == "POST":
claim_edit_form = ClaimEditForm(request.POST, instance=claim)
if claim_edit_form.is_valid(): # Validate transition rules

我错过了什么?谢谢。

最佳答案

问题原来是permission属性执行与源/目标验证器不同的验证。您必须评估在代码中其他地方的装饰器中建立的权限,而不是装饰器引发错误。因此,要从表单执行权限验证,您需要传入用户对象,在表单的 init 中接收用户。 ,然后与 has_transition_perm 的结果进行比较.所以这有效:

# model
@transition(field=state, source='prog', target='appr', permission='claims.change_claim')
def approve(self):
....

# view
if request.method == "POST":
claim_edit_form = ClaimEditForm(request.user, request.POST, instance=claim)
....

# form
from django_fsm import has_transition_perm

class ClaimEditForm(forms.ModelForm):
'''
Some users can transition claims through allowable states
(see permission property on claim.approve() decorator)
'''

def __init__(self, user, *args, **kwargs):
# We need to pass the user into the form to validate permissions
self.user = user
super(ClaimEditForm, self).__init__(*args, **kwargs)

def clean_state(self):
state = self.cleaned_data['state']
if state == 'appr':
if not has_transition_perm(self.instance.approve, self.user):
raise forms.ValidationError("You do not have permission for this transition")

关于django-fsm:权限不引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44599963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com