Django rules re-using predicate

202 Views Asked by At

I've created 2 predicate's, which are extremely similar in nature. One consumes a list and the other a static string.

@rules.predicate
def can_edit_items(user, fields):
    for perm in user.groups.all()
        if perm.name not in settings.fields[fields]
            return False
    return True

@rules.predicate
def can_edit_specific_item(user, field):
    for perm in user.groups.all()
        if perm.name not in settings.fields[field]
            return False
    return True

My requirements are that can_edit_specific_item() must make use of can_edit_items() by passing in a single string field_1

I've tried creating the following variation but it doesn't seem to work as I intend it to

@rules.predicate
def can_edit_specific_item(user, field):
    for perm in user.groups.all()
        if perm.name not in can_edit_items[field]
            return False
    return True
1

There are 1 best solutions below

0
David Silveiro On BEST ANSWER

You could define can_edit_specific_item by setting @rules.predicate inside can_edit_specific_item and returning this as a func, having only passed in your required field.

I'm a little unsure of the wider requirements, but maybe this might do the trick

def can_edit_specific_item(*field):
    @rules.predicate
    def predicate(user):
        return can_edit_items(user, field)
    return predicate