django - Show error message when decorator fails -
the decorator working fine display error message (i'd use messages framework) if user doesn't belong of required groups. here's decorator:
def group_required(*group_names): """requires user membership in @ least 1 of groups passed in.""" def in_groups(user): if user.is_authenticated(): if bool(user.groups.filter(name__in=group_names)) or user.is_superuser: return true return false return user_passes_test(in_groups)
i call using like:
@require_http_methods(['get']) @group_required('supervisor') def home_view(request): return render(request, 'home.html')
i tried using snippet use messages framework (since requires request object) realized messages framework middleware didn't appear installed inside decorator.
i'm willing change whatever takes :)
update:
what i'm looking for:
def group_required(request, *group_names): """requires user membership in @ least 1 of groups passed in.""" def in_groups(user): if user.is_authenticated(): if user.groups.filter(name__in=group_names).exists() or user.is_superuser: return true else: # i'm getting: # cannot add messages without installing django.contrib.messages.middleware.messagemiddleware messages.add_message(request, messages.error, 'group not allowed') return false return user_passes_test(in_groups, request)
i don't think need threadlocals in use case. , when threadlocals seems way go in django app, there mis-structured context layers. comparing w/ threadlocals, rather duplicate user_passes_test
, modify pass request
in_groups
(we not pass request
is_group
without modifying code of user_passes_test
. check question: how pass django request object in user_passes_test decorator callable function.) (maybe ticket this?)
furthermore, bool(user.groups.filter(name__in=group_names))
caused items retrieved db adapter , python instance before deciding existence, using exists()
, user.groups.filter(name__in=group_names).exists()
directly return bool result db backend far more efficient here.
Comments
Post a Comment